Hello -- On Tue, 31 Jul 2001, Yuguo Wang wrote: > Hi, all: > I am a new user of Ruby. Could anyone please tell me why in the > follwoing code, the string object is copied while the array is not. To > my understanding, dup and clone both should do shallow copy. > Thanks a lot. > > class A > attr_accessor :str, :ary > def initialize > @str = "hello" > @ary =[1,2,3,4] > end > > def to_s > puts "Str: #{@str}, Array: #{@ary} \n" > end > end > > a = A.new > b = a.dup > a.to_s ->Str: hello, Array: 1234 > b.to_s ->Str: hello, Array: 1234 > b.str = "Hello" > b.ary[0]="cat" > a.to_s ->Str: hello, Array:cat234 > b.to_s ->Str: Hello, Array:cat234 Neither underlying object is copied, just the instance variables themselves. The reason it looks like the string is copied is that you assign a new value to b's @str. At that point, a.str and b.str reference different strings. If you do this: b.str << ", world." instead of b.str = "Hello", you get: Str: hello, Array: 1234 Str: hello, Array: 1234 Str: hello, world., Array: cat234 Str: hello, world., Array: cat234 because with << you're modifying the referenced string, not pointing b.str at a different string. David -- David Alan Black home: dblack / candle.superlink.net work: blackdav / shu.edu Web: http://pirate.shu.edu/~blackdav