Karthick Karthick - 21 days ago 9
Ruby Question

ruby assign array to another variable and when delete element from that assign variable deleted on original array also

Am facing strange issue. I have an array below.

irb(main):007:0> original_array = []
=> []
irb(main):008:0> original_array.push("word1")
=> ["word1"]
irb(main):009:0> original_array.push("word2")
=> ["word1", "word2"]
irb(main):010:0> puts "#{original_array.inspect}"
["word1", "word2"]
=> nil
irb(main):011:0>


So when I have assigned this array to another array variable,

irb(main):011:0> assigned_array = []
=> []
irb(main):012:0> assigned_array = original_array
=> ["word1", "word2"]
irb(main):013:0>
irb(main):014:0> puts "#{assigned_array.inspect}"
["word1", "word2"]
=> nil
irb(main):015:0>


Now when I delete en element from the assigned_array its deleting from the original array also.

irb(main):015:0> assigned_array.delete("word2")
=> "word2"
irb(main):016:0> puts "#{assigned_array.inspect}"
["word1"]
=> nil
irb(main):017:0> puts "#{original_array.inspect}"
["word1"]
=> nil


Am not sure whether its the actual behavior of ruby. If so then is there any way to assign the original_array to assigned_array variable when I delete an element from assigned_array which shouldn't delete from original_array?

Answer

yes this is intended behavior of ruby. You can copy it by doing assigned_array = original_array.clone. Note: this creates a shallow copy (more info here https://en.wikipedia.org/wiki/Object_copying#Shallow_copy)

Assigning an non-literal from another non-literal (a = b) doesn't copy the contents of the object, just the reference. The result is that both original_array and assigned_array are the same instance of an array, so modifying one modifies the other, since they're the same object.

script example:

original_array = ["word1", "word2"]
puts original_array.inspect #=> ["word1", "word2"]
assigned_array = original_array.clone
assigned_array.delete("word2")
puts assigned_array.inspect #=> ["word1"]
puts original_array.inspect #=> ["word1", "word2"]
Comments