ruby - Arrays misbehaving -
here's code:
# = array.new(3, array.new(3)) = [[nil,nil,nil],[nil,nil,nil]] a[0][0] = 1 a.each {|line| p line}
with output:
[1, nil, nil] [nil, nil, nil]
but using commented line:
[1, nil, nil] [1, nil, nil] [1, nil, nil]
so why that?
the commented line assigning 3 of same reference array, change 1 array propagate across other references it.
as 2 arrays vs 3, that's matter of first line specifying 3 first parameter , specifying 2 array literals in second line.
to create nested arrays without having shared references:
a = array.new(3) {array.new(3)}
when passed block ({...}
or do ... end
), array.new call block obtain value of each element of array.
Comments
Post a Comment