From: "Daniel P. Zepeda" Date: 2003-01-30T13:34:15+09:00 Subject: Re: A simple program but strange output On Thu, 30 Jan 2003 13:13:43 +0900 "Maggie Xiao" wrote: > Hi there, > > I wrote a simple program to enumerate an array. The code is as below: > class Test > def initialize > @x=[0,1,2] > @tem=@x > @y=@x > y=del(@tem) > printf "#{@x}\n" > printf "#{@y}\n" > end > def del(x) > x.delete_at(0) > return x > end > end > a=Test.new > > But the output is : > 12 > 12 > Why @x and @y are changed? Is there anyone can tell me how to deal with > this problem? Because @tem is a reference (pointer) to the object, which is the array [0,1,2], and so is @y. @x,@y and @tem are all pointing to the same Array object, they are not different objects. If you want different objects, you have to make a copy: Here's an example using irb: irb(main):001:0> a = [0,1,2] => [0, 1, 2] irb(main):002:0> a.id => 537808534 irb(main):003:0> b = a => [0, 1, 2] irb(main):004:0> b.id => 537808534 irb(main):005:0> c = a.clone => [0, 1, 2] irb(main):006:0> c.id => 538070796 irb(main):007:0> > -- Daniel P. Zepeda