From: "David A. Black" Date: 2007-09-29T20:35:03+09:00 Subject: Re: Noobie question: saving the values Hi -- On Sat, 29 Sep 2007, Druhie Almighty wrote: > May you forgive me for this irrelevant thread but nonetheless, I need > your help. > I'm new at programming and recently I've faced with the problem > connected with the peculiarity of Ruby. Unlike many other languages, the > variables in it contain not the objects themselves but only links to > them, right? "Link" isn't the right word. Variables contain either the actual value of the object, or a reference to the object. It's not that peculiar, actually :-) > So can you please explain me why do these two operations very close to > each other result in different ways, considering the fact that both a > and b contain the same link? > > 1) > a="13" > b=a > a="12" As soon as you re-assign to a variable, you completely cut the previous assignment. b is still assigned to "13", but you're now using a to refer to a completely different object ("12"). > puts b --> 13 > > 2) > a="13" > b=a > a[1]="2" Here, you're not assigning a new object to a; rather, you're changing the object that a refers to. Since b refers to the same object, when you inspect b you see the change reflected. > puts b --> 12 > > To be more exact, in my program I need an array and a > variable=method(array). But when I call the method, the array itself > changes as well. How do I save the value of the array and get the > neccesary value of the variable at the same time? > P.S. And yes, I sought for solution in a guide but so far haven't found > anything. You can 'dup' the array, either before you call it or in the method: var = method(array.dup) Keep in mind, though, that the objects inside the array won't be duped. You're just creating a new array. So you can add objects to the new array (or delete objects from it) without affecting the original array. David -- Upcoming training from Ruby Power and Light, LLC: * Intro to Ruby on Rails, Edison, NJ, October 23-26 * Advancing with Rails, Edison, NJ, November 6-9 Both taught by David A. Black. See http://www.rubypal.com for more info!