我对循环遍历数组时更新数组的方式感到困惑。这是一个显示行为的虚构示例。
people = [{"name"=>"Edward", "age" =>"43", "height"=>"tallish"},
{"name"=>"Ralph", "age" =>"40", "height"=>"medium heigth"},
{"name"=>"George", "age" =>"35", "height"=>"very tall"},
{"name"=>"Mark", "age" =>"25", "height"=>"short"}]
numbers = ["1","3","26"]
new_array = []
numbers.each do |number|
people.each do |person|
person["name"] = person["name"] +" "+ number
new_array << person
end
end
在那个 new_array 的末尾是
[{"name"=>"Edward 1 3 26", "age"=>"43", "height"=>"tallish"},
{"name"=>"Ralph 1 3 26", "age"=>"40", "height"=>"medium heigth"},
{"name"=>"George 1 3 26", "age"=>"35", "height"=>"very tall"},
{"name"=>"Mark 1 3 26", "age"=>"25", "height"=>"short"},
{"name"=>"Edward 1 3 26", "age"=>"43", "height"=>"tallish"},
{"name"=>"Ralph 1 3 26", "age"=>"40", "height"=>"medium heigth"},
{"name"=>"George 1 3 26", "age"=>"35", "height"=>"very tall"},
{"name"=>"Mark 1 3 26", "age"=>"25", "height"=>"short"},
{"name"=>"Edward 1 3 26", "age"=>"43", "height"=>"tallish"},
{"name"=>"Ralph 1 3 26", "age"=>"40", "height"=>"medium heigth"},
{"name"=>"George 1 3 26", "age"=>"35", "height"=>"very tall"},
{"name"=>"Mark 1 3 26", "age"=>"25", "height"=>"short"}]
每个人出现 3 次,这是我所期望和想要的。但他们的名字每次都一样。我希望名字是"Edward 1"
第一次,然后是"Edward 1 3"
最后"Edward 1 3 26"
这里发生了什么?我认为循环会将每个单独的哈希附加到 new_array 上,而不是 3 都一样。