在rails上的ruby中为Hashing增值

时间:2017-09-06 10:36:13

标签: ruby-on-rails ruby hash

我有一个哈希,其数据类似于:

details = [{
  :project_name=>"ABC", :project_id=>12345, :total_count=>1, 
  :stories=>[#<TrackerApi::Resources::Story id=987654>]
}, {
  :project_name=>"XYZ", :project_id=>54321, :total_count=>1, 
  :stories=>[#<TrackerApi::Resources::Story id=123456>]
}]

我想插入另一个包含数据的数组,如:

sorter_Version = [["Abc ", "30 August 2017"], ["Not Accepted", "30 August 2017"]]

详细哈希,但不知何故无法做到。有人可以帮帮我。谢谢你。

输出应该是:

details = [{
      :project_name=>"ABC", :project_id=>12345, :total_count=>1, 
      :stories=>[#<TrackerApi::Resources::Story id=987654>],
      :sorter_version=>["Abc ","30 August 2017"]
    }, {
      :project_name=>"XYZ", :project_id=>54321, :total_count=>1, 
      :stories=>[#<TrackerApi::Resources::Story id=123456>],
      :sorter_version=>["Not Accepted ","30 August 2017"]
    }]    

1 个答案:

答案 0 :(得分:1)

只需使用each_with_index

details.each_with_index { |d, i| d[:sorter_version] = sorter_Version[i] }
#=> [{:project_name=>"ABC", :project_id=>12345, :total_count=>1, 
#     :stories=>["#<TrackerApi::Resources::Story id=987654>"], 
#     :sorter_version=>["Abc ", "30 August 2017"]}, 
#    {:project_name=>"XYZ", :project_id=>54321, :total_count=>1, 
#     :stories=>["#<TrackerApi::Resources::Story id=123456>"], 
#     :sorter_version=>["Not Accepted", "30 August 2017"]}]

不可变版本:

details.map.with_index { |d, i| d.merge(sorter_version: sorter_Version[i]) }