繁体   English   中英

Ruby:将哈希添加到主哈希不会返回任何内容

[英]Ruby: adding a hash to a master hash returns nothing

我正在用Ruby写一个小的CSV解析器。 CSV解析器可以正常工作,但是我无法将row添加到hash 我究竟做错了什么?

这是解析器:

require 'smarter_csv'

f = File.open('installs.csv')
hash = {}

csv = SmarterCSV.process(f, strip_chars_from_headers: /"|:/)
csv.each do |row|
  coords = row[:location_1].lines.to_a[1..-1].join
  row[:address] = coords
  hash << row
end

p hash

undefined method '<<' for {}:Hash (NoMethodError)错误返回undefined method '<<' for {}:Hash (NoMethodError) 这是怎么回事?

您可以使用合并! 将Hash插入另一个Hash,其行为类似于Array <<

a = {'1' => 2}
b = {'2' => 3}
c = {}
c.merge!(a) # c = {'1' => 2}
c.merge!(b) # c = {'1' => 2, '2' => 3}

如果你想要一个ArrayHashes ,你为什么不使用Array对象,而不是散列

require 'smarter_csv'

f = File.open('installs.csv')
a = []

csv = SmarterCSV.process(f, strip_chars_from_headers: /"|:/)
csv.each do |row|
  coords = row[:location_1].lines.to_a[1..-1].join
  row[:address] = coords
  a << row
end

p a # will result in array of rows, each row is hash

对于哈希使用合并或合并! 用! 保留对对象的更改。

hash_one = {a: 1, b: 3, c: 2}
=> {a: 1, b: 3, c: 2}
hash_two = {d: 89, e: 34, f: 1}
=> {d: 89, e: 34, f: 1}
hash_two.merge!(hash_one)
=> {a: 1, b: 3, c: 2, d: 89, e: 34, f: 1}

对数组对象使用<<。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM