From: David Milne Date: 2004-01-09T01:46:41+09:00 Subject: Re: I don't understand this behavour, is it a bug? "Mark J. Reed" wrote in message news:20040108160145.GB2444@mulan.thereeds.org... > On Fri, Jan 09, 2004 at 12:28:38AM +0900, David Milne wrote: > > Please I wonder if any one can give me some advice? > > > > I thought I would get into Ruby by "writing BASIC scripts in Ruby". I > > thought I would try to write one script fragment each day. > > My latest script fragment has a behavour which I do not understand. Is it a > > bug? > > > I give variable one a value of [1, 2, 3, 4, 5] . I then set variables two > > and three equal to variable one. I then do stuff to three using one to give > > three the value [1, 3, 6, 10, 15]. My little scrip then prints out variables > > one, two and three. I am amazed to find that one and two appear in the > > printout to have altered them selves to look like three, that is one == two > > == three == [1, 3, 6, 10, 15]. > > No, it's not a bug. In Ruby and most OO languages, variables don't > contain the actual objects; they contain references or pointers to the > objects. So when you make an assignment, the reference is copied, but it's > still referencing the same actual object. You wind up with multiple variables > pointing to the same object. > > If you want to make a duplicate of an object, you have to do so explicitly > by calling the clone method, e.g. > > one = [1, 2, 3, 4, 5] > two = one.clone > three = one.clone > > -Mark Thanks very much Peter and Mark. I got the business about the pointers and the clone method. I had been starting to feel real uptight :-) David