Hi --

On Thu, 14 Dec 2006, Christopher Coleman-Smith wrote:

> Simple question, i come from a C/++ background and i'm just really starting 
> to get "real things done with ruby" ( that should be a book title). Anyway as 
> i start writing methods that return objects and variables and take objects 
> and variables i've started to wonder how they actually get passed around. I 
> haven't found a specific pointer or reference type construction, although 
> since everything i've tried to do has worked i've not tried very hard.
>
> I'm guessing that everything gets passed around by reference? Is that true? 
> Also what about situations where you'd really want to use a pointer, like 
> referring to huge things or ,god forbid, doing grimy things with arrays. It 
> is very nice having all these things automated, like the garbage collection 
> etc, but i still find myself wanting to free things. I've only just gotten 
> over wanting to semi-colon every statement.

Basically, everything (or almost everything) is a reference:

   a = [1,2,3]   # a is assigned a reference to the array
   b = a         # b gets a copy of that reference
   b.push(4)     # the array now has four elements
   p a           # as you'll see if you print it via any reference

When you pass objects around via variables, technically you're passing
by value...  but the "value" of the variable is a reference to an
object.

When you pass objects around via literals (like puts "hello"), a
reference to the literal is sent.

All of this means that if you do something to the arguments in a
method, the changes are permanent in the original object:

   def add_element(array)
     array.push("new element!")
   end

   a = [1,2,3]
   add_element(a)
   p a

So you'll see a fair amount of "dup"ing going on in methods that want
to be safe.

There's no reference-to-a-reference.  It's not like C pointers, which
can point to other pointers.  Every Ruby reference is exactly one step
away from the object it refers to, and all references to an object are
equivalent to all other references to that object.

Some values are immediate; i.e., when you assign a variable to them,
they get stored directly and not via a reference: integers, true,
false, nil, and symbols (and any I've forgotten).  Hence the "almost
everything" above.


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)