From: Stefano Crocco Date: 2007-02-25T06:25:30+09:00 Subject: Re: Just started learning Ruby Alle sabato 24 febbraio 2007, DracoJK ha scritto: > I've been working through the Humble Ruby Book that I found in a signature > of one of ruby talk's list members, and would like a little more > explanation as to how pointing to a pointer works. > > The example used was a string: > > first_var = "i hold a reference" > → i hold a reference > second_var = first_var > → i hold a reference > second_var.chop! # Chops off the last character of the string > → i hold a referenc > first_var > → i hold a referenc > > This works fine... I understand this... but I tried it with an integer > rather than a string, and it doesn't seem to work how I expect it to. > > first_var = 1 > second_var = first_var > second_var += 1 > puts first_var > > this outputs 1, but I thought it'd output 2... o_O > > What's the difference? Why do variables work differently with integers as > opposed to strings? > > Thanks for answering my ever so simple question. :) I come from a java > background and never really thought about how things work when you point a > variable to another variable. :P In both cases, writing second_var=first_var makes the two variables contain the same object (you can see this by using the object_id method). The chop! method changes the contents of its receiver, that is of the string contained by both first_var and second_var. On the other hand, in your second example, when you write second_var+=1, which is translated to second_var=second_var+1, you're storing a different value in second_var, not changing the object it contains. Note that the difference isn't due to the fact that in the first case you're using strings and in the second case you're using integers (although integers have some peculiarities, in particular, there's only one integer object for each number). If you do something like: first_var="a string" second_var=first_var #now first_var and second_var contain the same object second_var=second_var.chop #chop doesn't modify the original string puts second_var => a strin puts first_var => a string you get the same behaviour you got with integers. I hope this helps Stefano