遍历哈希数组并更新每个哈希

时间:2018-10-10 07:29:01

标签: arrays ruby hash

我有一系列的哈希,如下所示:

data[:array] = [{:a=>"a", :b=>"b"}, {:a=>"a", :b=>"b"}]

我需要使用新的键值对更新每个哈希,如下所示。

data[:array] = [{:a=>"a", :b=>"b", :c=>"c", :d=>"d"},
                {:a=>"a", :b=>"b", :c=>"c", :d=>"d"}]

我正在尝试执行以下操作:

data[:array].each do |array|
  c_info = fetch_c(args: args) # Say fetch_c gives out c as output 
  d_info = fetch_d(args: args) # Say fetch_d gives out d as output 
  array.merge!(c: c_info, d: d_info)
end

我得到输出:

data[:array] = [{:a=>"a", :b=>"b", :c=>"c", :d=>"d"},
                {:a=>"a", :b=>"b"}]

在第二次迭代中不更新哈希。请提出建议。

1 个答案:

答案 0 :(得分:0)

我能重现此问题的唯一方法是在fetch_cfetch_d之间抛出错误。

复制步骤:

def fetch_c(i)
  10/i
end

data[:array] = [{:a=>"a", :b=>"b"},{:a=>"a", :b=>"b"}]

data[:array].each_with_index do |array, index|
    c_info = fetch_c(index-1)
    d_info = fetch_c(index-1)
    array.merge!(c: c_info, d: d_info)
end
# ZeroDivisionError: divided by 0

data
# => {:array=>[{:a=>"a", :b=>"b", :c=>-10, :d=>-10}, {:a=>"a", :b=>"b"}]}

请确保您的方法不会引发错误。