【问题标题】:Ruby: adding a hash to a master hash returns nothingRuby:向主哈希添加哈希不会返回任何内容
【发布时间】:2023-03-03 06:02:19
【问题描述】:

我正在用 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 '&lt;&lt;' for {}:Hash (NoMethodError) 错误。怎么回事?

【问题讨论】:

  • 你所说的hash应该是一个数组实例。

标签: ruby-on-rails ruby csv hash


【解决方案1】:

您可以使用merge! 将Hash 插入另一个Hash,它的行为类似于Array &lt;&lt;

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

如果你想要HashesArray,为什么不使用Array 对象而不是Hash

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

【讨论】:

  • 这很好,但是如果我要迭代每个合并呢?只有最后一个row 存在于hash 中。
【解决方案2】:

对于哈希使用合并或合并!和 !持久化对对象的更改。

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}

使用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-23
    • 1970-01-01
    • 2011-05-19
    • 2021-02-05
    • 2019-10-24
    • 2014-02-22
    • 2015-08-09
    相关资源
    最近更新 更多