Pass by reference versus pass by value

Posted on: Friday, Mar 7, 2014

I’m currently studying Ruby and Rails with the Tealeaf Academy. It’s going well and it’s really fun to study Ruby. After years of Java, I feel Ruby is being a step forward.

During the study, the subject of Ruby’s passing by reference or passing by values.  (For the less-technical readers; this is the difference between passing the value of a variable to a method or passing only a reference to the value to a method. The latter enables the possibility of modifying the original variable by using the reference.)

Unfortunately, the whole subject of Ruby being either pass by reference or pass by value wasn’t clear to me. So I did some Googling to find out the answer. This confused me even more because some people are convinced it’s pass by reference and others are convinced it’s pass by value.
Having a Java background, I was convinced it’s pass by reference as it’s possible to modify the original object in a method using the method parameter as a reference.

Turns out, it’s neither or both (just how you look at it). I’ve found some (blog) posts which explained it pretty clear to how Ruby behaves. I want to share these with you;

The ‘conclusion’ is that Ruby is pass-by-value, but to be perfectly correct and explicit, we should really say that Ruby is pass-by-value-of-the-reference or pass-by-value where the value is a reference. Sounds a bit confusing, but this explanation clarifies the point:

Pass-by-reference means that the actual reference is passed to the method. This allows the reference (and/or the referenced object) to be manipulated in the method and those changes to be reflected once the method returns. Both the object and the reference copy can be manipulated.

Pass-by-value where the value is a reference means that a copy of the reference is passed to the method. The scope of this reference copy is just within the method. This allows the referred-to object to be manipulated via the reference copy and those changes would be reflected on return of the method. BUT any changes made to the reference copy itself will not be reflected on return of the method. The object can be manipulated, but not the reference copy.

Source: the tourist – Ruby: Pass-by-Reference or Pass-by-Value?

The following post on StackOverflow confirms this by referencing to a paragraph from the O’Reilly book, The Ruby Programming Language:
http://stackoverflow.com/a/18069011
(Note; the rest of the StackOverflow page contains some contradicting and confusing comments.)