Devin Mullins
6/18/2005 12:08:00 AM
As in many modern languages (Java, most popularly, but I'd imagine
Python, too), everything's a pointer, so to speak. If you want a copy,
you should say b=a.dup, instead. Note, however, that not even that's
perfect.
While this works:
irb(main):001:0> a=[1,2,3,4,5]
=> [1, 2, 3, 4, 5]
irb(main):002:0> b=a.dup
=> [1, 2, 3, 4, 5]
irb(main):003:0> b[2]=7
=> 7
irb(main):004:0> a
=> [1, 2, 3, 4, 5]
irb(main):005:0> b
=> [1, 2, 7, 4, 5]
irb(main):006:0>
There is still a pitfall if the Objects that your Array contains are
mutable (changeable):
irb(main):006:0> a=["hello","dog","cat"]
=> ["hello", "dog", "cat"]
irb(main):007:0> b=a.dup
=> ["hello", "dog", "cat"]
irb(main):008:0> b[2]="feline"
=> "feline"
irb(main):009:0> b[1].reverse!
=> "god"
irb(main):010:0> a
=> ["hello", "god", "cat"]
irb(main):011:0> b
=> ["hello", "god", "feline"]
irb(main):012:0>
Note that b[2]=... makes the new separate b Array point to a brand new
String object, while b[1].reverse! modifies the existing String object
-- the one that both a and b both point to. This is because Array#dup
(and in general Object#dup) is a shallow copy. In other words,
Object#dup is not "recursive" on the Objects inside.
Hope that helps, and hope it doesn't kill your buzz. :)
Devin