Why does array.each behavior depend on Array.new syntax?

后端 未结 3 436
遇见更好的自我
遇见更好的自我 2020-12-11 05:13

I\'m using Ruby 1.9.2-p290 and found:

a = Array.new(2, []).each {|i| i.push(\"a\")}    
=> [[\"a\", \"a\"], [\"a\", \"a\"]]

Which is not

3条回答
  •  长情又很酷
    2020-12-11 05:54

    This is a common misunderstanding. In your first example you are creating an array with 2 elements. Both of those are a pointer to the same array. So, when you iterate through your outer array you add 2 elements to the inner array, which is then reflected in your output twice

    Compare these:

    > array = Array.new(5, [])
    => [[], [], [], [], []] 
    
    # Note - 5 identical object IDs (memory locations)
    > array.map { |o| o.object_id }
    => [70228709214620, 70228709214620, 70228709214620, 70228709214620, 70228709214620] 
    
    > array = Array.new(5) { [] }
    => [[], [], [], [], []] 
    
    # Note - 5 different object IDs (memory locations)
    > array.map { |o| o.object_id }
    => [70228709185900, 70228709185880, 70228709185860, 70228709185840, 70228709185780] 
    

提交回复
热议问题