> 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

Yes, the default implementations of Object#dup and Object#clone do a shallow
copy. So after executing:

a = A.new
b = a.dup

both "a" and "b" hold references to the same string and array, i.e.

a.str.id == b.str.id    AND   a.ary.id = b.ary.id

so when you modify the first element of the array pointed to by b.ary:

b.ary[0] = "cat"

you're modifying the first element of the same array that a.ary points to.
You still haven't created a *new* Array object anywhere. You'd see something
different, however, if you did this:

a = A.new
b = a.dup
b.str = "Hello"
b.ary = [4, 3, 2, 1]
a.to_s -> Str: hello, Array:1234
b.to_s -> Str: Hello, Array: 4321

Now b.ary points to an entirely different array.

Hope this helps,

Lyle