Of course, I just intended to change the first value, not both of them.
Can anybody explain please what I can do about this?
You need to use .dup:
a = ["ABC", "30", "1"]
=> ["ABC", "30", "1"]
b = a.dup
=> ["ABC", "30", "1"]
b[0] = "DEF"
=> "DEF"
a
=> ["ABC", "30", "1"]
b
=> ["DEF", "30", "1"]
If you just assign an object, you get another reference to the same
object. DUP will give you a copy, although not a deep copy. That means
that if
a = [["ABC", "30", "1"]], a.dup will not give you a copy of the
element within the array - it will give you a copy of the array with
the inner element being a reference again:
Dunno if you can understand german.. at least the examples are in
english, maybe you understand what is going on despite being unable to
understand anything
Indeed - it only cloned the top level of a, which is an array. The rest remained a linked-too object.
How to deep clone?
Dunno if you can understand german.. at least the examples are in english, maybe you understand what is going on despite being unable to understand anything
Indeed - it only cloned the top level of a, which is an array. The rest remained a linked-too object.
How to deep clone?
The most common idiom for deep copying is:
copy = Marshal.load(Marshal.dump(original))
David
--
Rails training from David A. Black and Ruby Power and Light:
Intro to Ruby on Rails July 21-24 Edison, NJ
Advancing With Rails August 18-21 Edison, NJ
See http://www.rubypal.com for details and updates!