Variables and References

Hi,

I'm new to ruby. Trying to understand how variables hold references to
objects.
I wrote some simple example for this:

···

##
# Trying to observ person1 and person2 are aliases.
# (they references the same object)

person1 = "Tim"
person2 = person1
person2[0] = "s" # This changes both

puts person1
puts person2

# Produces:
#
# Tim
# sim

# Second part
person3 = "Tim"
person4 = person3
person4 = "s"

puts person3
puts person4

# Produces:
#
# Tim
# s

I expect that the second part will print:
s # not Tim
s

What's the reason that when I assign something to person3, person4
doesn't change although they are aliases (or aren't they?)

Thanks,
Aytek

Hi --

···

On Fri, 15 Dec 2006, Aytek Yüksel wrote:

What's the reason that when I assign something to person3, person4
doesn't change although they are aliases (or aren't they?)

When you do an assignment, you wipe out that variable's previous
reference, if any. You're re-using the identifier person3, and thus
breaking its connection with the object that both it and person4
referred to.

David

--
Q. What's a good holiday present for the serious Rails developer?
A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black\)
    aka The Ruby book for Rails developers!
Q. Where can I get Ruby/Rails on-site training, consulting, coaching?
A. Ruby Power and Light, LLC (http://www.rubypal.com)

Aytek Yüksel wrote:

/ ...

What's the reason that when I assign something to person3, person4
doesn't change although they are aliases (or aren't they?)

person1 = "Tim"
person2 = person1
person2[0] = "s" # This changes both

In this example, you changed one character of an existing object, a string,
but you did not create a new object. The change you made was reflected in
both references to that object.

person3 = "Tim"
person4 = person3
person4 = "s"

In this example, you caused a variable to refer to an entirely new object,
abandoning the old object reference.

Any time you can manipulate the content of an object without creating a new
object, all references to that object will show the change.

But if you cause one object to be replaced by another, the referring
variable will refer to the new object and abandon the old.

···

--
Paul Lutus
http://www.arachnoid.com

I did a silly mistake.
Thank you Paul and David for your great answers.

Aytek

Aytek Yüksel wrote:

I did a silly mistake.

No, not at all. Yours wasn't a silly mistake, it was a very good question.
If I had seen what you did, at your experience level, I would certainly
have wanted an explanation.

The silly people are the ones who can't bring themselves to ask questions.

···

--
Paul Lutus
http://www.arachnoid.com