1

我对循环遍历数组时更新数组的方式感到困惑。这是一个显示行为的虚构示例。

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 都一样。

4

2 回答 2

1

people.each为您提供对 中每个条目的引用people,因此当您person["name"] =...修改原始数组时。

尝试这个:

numbers.each do |number|
    people.each do |person|
        new_person = person.dup
        new_person["name"] << " " + number
        new_array << new_person
    end
end
于 2012-04-23T12:56:43.547 回答
0

您可以稍微转换一下代码以查看该过程

numbers.each do |number|
    people.each do |person|
        person["name"] = person["name"] +" "+ number
        new_array << person
        puts person["name"]
    end
end

你会得到这样的结果:

Edward 1
...
Edward 1 3
...
Edward 1 3 26
...

如您所见,该算法几乎按照您的预期工作。但是person["name"]仅引用一个对象(字符串),这就是最终结果具有最后一个字符串的原因Edward 1 3 26

编辑:为了得到你想要的,你应该每次都创建新对象

numbers.each do |number|
  people.each do |person|
    person["name"] = person["name"] +" "+ number
    new_array << person.dup
  end
end

不要忘记重新初始化 people 变量,因为这个表达式

person["name"] = person["name"] +" "+ number

修改人员变量。

于 2012-04-23T13:01:10.823 回答