如何克隆哈希数组并使用每个循环添加键值

问题描述 投票:0回答:1

我想克隆一组哈希,然后将其克隆到多个哈希中。

irb(main):001:0> arr = [{a: "one", b: "two"}, {a: "uno", b: "due"}, {a: "en", b: "to"}]
=> [{:a=>"one", :b=>"two"}, {:a=>"uno", :b=>"due"}, {:a=>"en", :b=>"to"}]
irb(main):002:0> arr_1 = arr.clone
=> [{:a=>"one", :b=>"two"}, {:a=>"uno", :b=>"due"}, {:a=>"en", :b=>"to"}]
irb(main):003:0> arr_2 = arr.clone
=> [{:a=>"one", :b=>"two"}, {:a=>"uno", :b=>"due"}, {:a=>"en", :b=>"to"}]

动态地,我想将id添加到哈希中。

irb(main):004:0> arr_1.each { |k| k[:id] = 1 }
=> [{:a=>"one", :b=>"two", :id=>1}, {:a=>"uno", :b=>"due", :id=>1}, {:a=>"en", :b=>"to", :id=>1}]
irb(main):005:0> arr_2.each { |k| k[:id] = 2 }
=> [{:a=>"one", :b=>"two", :id=>2}, {:a=>"uno", :b=>"due", :id=>2}, {:a=>"en", :b=>"to", :id=>2}]

但是arr_1id的结果会受到arr_2成为2的每个循环操作的影响>

irb(main):006:0> arr_1
=> [{:a=>"one", :b=>"two", :id=>2}, {:a=>"uno", :b=>"due", :id=>2}, {:a=>"en", :b=>"to", :id=>2}]

我尝试使用

arr_1 = arr
arr_2 = arr

但是结果始终显示相同的结果。如何使arr_1散列:id = 1arr_2散列:id = 2

我想克隆一组哈希,然后将其克隆到多个哈希中。 irb(main):001:0> arr = [{a:“ one”,b:“ two”},{a:“ uno”,b:“ due”},{a:“ en”,b:“ to“}] => [{:a =>” one“,:b =>” ...

ruby-on-rails ruby hash iteration
1个回答
0
投票

您需要类似以下内容的东西。

© www.soinside.com 2019 - 2024. All rights reserved.