2007/7/27, Phlip email@example.com:
if i pass arguments in a function then they get passed by value.
Ruby supports two kinds of variables; IIRC numbers, characters, booleans,
and nil are “immediate”, and everything else is a reference to an object.
Personally I find it easier to grasp (especially when starting out
with Ruby) this when you assume that everything is an object.
Although there are some optimizations going on behind the scenes all
objects behave the same - from a Ruby user’s perspective. This is
totally different from Java’s handling of PODs for example.
The best way to explain this is to look at Ruby’s source. A VALUE is the
union of a long and a pointer. Anything small enough to fit in a long is an
immediate value, and everything else uses the pointer to point to a
Again, I would not start with Ruby sources here.
So at function call time, Ruby passes the VALUE by value. So immediates
get copied, and objects get passed by reference.
I think “pass by reference” is not the proper term because that would
imply that you could change a variable in the calling scope, i.e. you
def magic(x) x = 10 end
foo = 1
puts foo # prints 1
puts foo # prints 10
which you can’t. I’d rather call it “call by reference value”, i.e.
the reference is copied.
So, in addition to your other answer, you could also put your referend into
a class, and pass this around. That might fit the ideals of Object Oriented
Programming better than passing immediates would.
I am not sure why you refer to immediates here. Using instance
variables is generally one of the core OO techniques.