Variables and References

A

Aytek Yüksel

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
 
D

dblack

---2049402039-200301060-1166139176=:7735
Content-Type: MULTIPART/MIXED; BOUNDARY="-2049402039-200301060-1166139176=:7735"

This message is in MIME format. The first part should be readable text,
while the remaining parts are likely unreadable without MIME-aware tools.

---2049402039-200301060-1166139176=:7735
Content-Type: TEXT/PLAIN; charset=X-UNKNOWN; format=flowed
Content-Transfer-Encoding: QUOTED-PRINTABLE

Hi --

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

--=20
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)
---2049402039-200301060-1166139176=:7735--
---2049402039-200301060-1166139176=:7735--
 
A

Aytek Yüksel

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

Aytek
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,220
Messages
2,571,128
Members
47,744
Latest member
FrederickM

Latest Threads

Top