From: Hal Fulton Date: 2005-11-12T15:57:45+09:00 Subject: Re: Function Variable and Return Value References Eric Hofreiter wrote: > In C++, one thing that is certain is that all variables passed into functions and all return values are actually copies. Therefore, the functions can't manipulate their arguments directly. As everyone knows, the easiest way to get this effect is to pass in by reference. This way a copy is not made; the actual variable is passed in, allowing direct modification. A similar idea can be used with return values or even without a function at all. > > The question is, how exactly does ruby behave in this respect? I haven't quite figured out what the rules are. It appears that Fixnum and basically every user-made object are always passed by value, and can not reference each other. However, arrays seem to be passed into functions by reference, and returned by value, though the objects they contain are copied. > > 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. So that brings me to my second question: what are the purpose of the methods dup and clone? I thought they would be useful if you needed to assign copies rather references, but it seems that objects are copied by default when assigned. Can someone please explain this to me? You're on the right track, you just have a few misunderstandings. First of all, variables in Ruby *do* hold references to objects (except in the cases where the values are "immediate" -- Fixnum for example). But remember that assignment is not a method in Ruby. Assignment can't be overridden or any such thing. (Well, an attr_writer gives you something that looks like assignment, but it's really just a bit of syntax sugar.) So any operation that actually *changes* the object will behave as you expect. a = "Hello" a = b b << " there!" puts a # "Hello there!" puts b # "Hello there!" However, any operation that binds a variable to a new/different object won't show that effect. a = "Hello" a = b b += " there!" puts a # "Hello" puts b # "Hello there!" You might think at first glance that x << y and x += y do the same thing for strings. And indeed they result in the same value. But x += y is just syntax sugar for x = x + y (i.e., they mean *exactly* the same thing). So += is actually an assignment, and thus doesn't change an object -- it just binds a variable to a new or different object. The example shown above would work the same way for arrays. But it wouldn't make any sense for Fixnums -- they are immediate values, and anyhow are immutable. (All immediate values are immutable, but some "real objects" are immutable also -- e.g., a Time value.) Does that help some?? Hal