ruby - Changing an array -
i created array way:
arr = array.new(4, array.new(4, '*'))
when try change 1 element, example first element of first array:
arr[0][0] = 3
then every first element changed.
print arr [[3, "*", "*", "*"], [3, "*", "*", "*"], [3, "*", "*", "*"], [3, "*", "*", "*"]]
can explain why happening?
do:
arr = array.new(4) { array.new(4, '*') }
ruby array in fact set of pointers, points onto other objects n memory. in code pointers point same object created array.new(4, '*')
. if, instead of value, pass block, block executed every element of array, each pointer point new object in memory.
in fact, code above still have similar issue string '*'. should use same method fix it:
arr = array.new(4) { array.new(4) { '*' } }
Comments
Post a Comment