[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Variables and References

Aytek Yüksel

12/14/2006 11:29:00 PM

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

4 Answers

dblack

12/14/2006 11:33:00 PM

0

Paul Lutus

12/14/2006 11:38:00 PM

0

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.ara...

Aytek Yüksel

12/14/2006 11:45:00 PM

0

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

Aytek

Paul Lutus

12/14/2006 11:56:00 PM

0

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.ara...