Otelo Otelo - 4 months ago 17
Ruby Question

In Ruby when I set array X equal array Y and make chages to array X why is it also made to array Y?

In this code:

letters = %w{a b c d e f g}
letters_2 = letters

i = 0
while i < letters.length
letters[i] = "X"
puts "letters = " + letters.join
puts "letters_2 = " + letters_2.join
puts "======================"


why does letters_2 array get changed when the code is only explicitly modifying the letters array?


In your example, there is only one array, and letters and letters_2 are both assigned to it.

It sounds like what you want is for letters_2 be a separate array, that's initialized from the letters array, but independent thereafter? If so, then one way to do that is to use the Array.new method:

letters = %w{a b c d e f g}
letters_2 = Array.new(letters)
# letters and letters_2 are now separate arrays with the same elements

letters[3] = "X" # this only affects letters, not letters_2
letters_2[4] = "Y" # this only affects letters_2, not letters