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

后端 未结 3 441
遇见更好的自我
遇见更好的自我 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 06:03

    From the ruby documentation:

    new(size=0, obj=nil)
    new(array)
    new(size) {|index| block }
    

    Returns a new array. In the first form, the new array is empty. In the second it is created with size copies of obj (that is, size references to the same obj). The third form creates a copy of the array passed as a parameter (the array is generated by calling to_ary on the parameter). In the last form, an array of the given size is created.

    Thus, in the a array you create, you have two references to the same array, thus the push works on both of them. That is, you're pushing "a" onto the same array twice. In the the b array you create, you're actually creating a new array for each element.

提交回复
热议问题