I have the following code as an example.
a = [2]
b = a
puts a == b
a.each do |num|
a[0] = num-1
end
puts a == b
I want b
to refer to a
's value, and the value of b
not to change when a
is changed.(The second puts
should return false).
Thank you in advance.
Edited-
The answer posted by user2864740 seems to work for the example I gave. However, I'm working on a sudoku solving program, and it doesn't seem to work there.
@gridbylines = [[1,0,0,9,2,0,0,0,0],
[5,2,4,0,1,0,0,0,0],
[0,0,0,0,0,0,0,7,0],
[0,5,0,0,0,8,1,0,2],
[0,0,0,0,0,0,0,0,0],
[4,0,2,7,0,0,0,9,0],
[0,6,0,0,0,0,0,0,0],
[0,0,0,0,3,0,9,4,5],
[0,0,0,0,7,1,0,0,6]]
save = Array.new(@gridbylines) #or @gridbylines.dup
puts save == @gridbylines #returns true
puts save.equal?(@gridbylines) #returns false
@gridbylines[0][0] = 'foo'
puts save.equal?(@gridbylines) #returns false
puts save == @gridbylines #returns true, but I want "save" not to change when I change "@gridbylines"
Does this have something to do with the fact that I'm using a global variable, or the version of Ruby I'm using, or even because it's a multidimentional array unlike the previous example?