Blog
Posts tagged with "Call by Value".
Does Ruby call by reference or by value?
Stephen
02 Nov 2009 15:20
There is a surprising amount of discussion on this topic, some with convincing examples supporting one or other side of the fence. So I thought I’d have a go at explaining it…. Ruby uses call-by-value. There I’ve said it, now for the backup.
It hinges on the clarification between call-by-reference and call-by-value where the value is a reference which Ruby uses.
Call-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.
Call-by-value where the value is a reference – means 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.
E.g. assigning a new object to the reference copy would only have the scope of that method, i.e. on return the original reference would be unchanged.
I think this explains the behaviour in the examples I have seen.

