From: Eric Mahurin Date: 2005-11-12T23:58:37+09:00 Subject: Re: Function Variable and Return Value References On 11/11/05, Eric Hofreiter wrote: > At first, I thought variables were always pointers, and things such as a = b meant that if you change a, you change b. It seems now that this is in fact never the case. Actually, I think of ruby variables as pointers (like a void * in C/C++ - no particular pointer type). Looking at Hal's example, here's how you might equate C++ and ruby (my C++ isn't so good): a = "Hello" # string a0 = "Hello" # string *a = &a0 b = a # string *b = a c = a # string *c = a b += " there!" # b = &(*b + " there!") puts a # cout << *a # => "Hello" puts b # cout << *b # => "Hello there!" puts c # cout << *c # => "Hello" c << " world!" # c->append(" world!") puts a # cout << *a # => "Hello world!" puts b # cout << *b # => "Hello there!" puts c # cout << *c # => "Hello world!" For all but immediate objects this is pretty much how variables are implemented - as object pointers/references. Even for immediate objects (Fixnum, Symbol, true, false, nil), you can also think of them the same way. Since immediate objects are immutable and don't require much data (at most 31 bits), they can be encoded right into the pointer directly (all other normal object pointers are aligned to 32-bit boundaries so that the bottom 2 bits are 0 - immediates may put ones here). What you can't easily do is get a reference to a variable itself. Since variables hold references to objects, you'll find this is seldom wanted. I have had several occasions though and had to find another (less elegant) way around. It would be kind of nice if there was a heavier weight variable (like C++ reference variable) where you could control what methods to use for getting and setting the variable. Some other pure OO languages (i.e. self) treat a variable as an object with get and set methods. With ruby they are lightweight, which makes it easy to make them efficient.