On Sat, 29 Sep 2007, Druhie A. wrote:
May you forgive me for this irrelevant thread but nonetheless, I need
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
“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,
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?
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
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
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