Possible Duplicate:
Is Ruby pass by reference or by value?
Working with Ruby, when passing an object to a method, how is the memory of this object handled?
Coming from a C background, I can think of several things which may be happening:
-
A copy of the memory associated with the according object and is made available to the method being called. In which case the modification of the object would only be reflected in the context of method being called, and not the calling method.
-
A reference to the memory of the object is passed the method being called (essentially a pointer). Hence any changes made by the object by the method being called or the calling method would be reflected in both contexts. As well, should this program be multithreaded, some kind of mechanism (mutex, semaphore, etc.) must be used to ensure mutually exclusive access to that memory performing write operations.
-
Something else I am unable to think of… maybe a memory model similar to that of Go… Pipes… MessagePassing…?
What is actually happening?
Ruby uses pass-by-value, or more precisely, a special case of pass-by-value where the value being passed is always a pointer. This special case is also sometimes known as call-by-sharing, call-by-object-sharing or call-by-object.
It’s the same convention that is used by more or less every object-oriented language ever created.
Note: on all existing Ruby implementations
Symbols,Fixnums andFloats are actually passed directly by value and not with an intermediary pointer. However, since those three are immutable, there is no observable behavioral difference between pass-by-value and call-by-object-sharing in this case, so you can greatly simplify your mental model by simply treating everything as call-by-object-sharing. Just interpret these three special cases as internal compiler optimizations that you don’t need to worry about.Here’s a simple example you can run to determine the argument passing convention of Ruby (or any other language, after you translate it):
In short: it’s your option 2.