Ruby 2D Array Assignment Possible Bug? -
i'm experiencing following. expect first sub-element of first sub array assigned "x"
, not first element of each sub array. can explain behaviour, , perhaps how work around it? (note may expected behaviour, if is, contradicts expectations.)
x = array.new(3, array.new(5)) # => [[nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil]] x[0][0] # => nil x[0][0] = "x" x # => [["x", nil, nil, nil, nil], ["x", nil, nil, nil, nil], ["x", nil, nil, nil, nil]]
workaround :
x = array.new(3) { array.new(5) } x[0][0] = 'a' x # => [["a", nil, nil, nil, nil], [nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil]]
here array of given size created. each element in array created passing element’s index given block , storing return value.
read common gotchas
when sending second parameter, same object used value array elements. since array elements store same array
array.new(5)
, changes 1 of them affect them all.if multiple copies want, should use block version uses result of block each time element of array needs initialized, did above.
Comments
Post a Comment