Monthly Archives: October 2013

Exploring copy, swap, and argument passing in Ruby

Modifying a variable of type Fixnum passed to a method

I had a need to pass in a variable of Fixnum type to a method and use the method to update its value.    This wasn’t quite as straightforward as I had hoped.

The first question I needed to answer was how arguments were passed into methods – call by reference or call by value?

I found a lot of discussion about this in post such as void foo(int &x) -> Ruby? Passing integers by reference?  and Are arguments passed to methods by reference or value?

My takeaway was that variables are passed by value, but that those variables are references to objects.    With an object such as an Array or Hash, you can modify elements of the object using the passed (immutable) reference.  The problem with a Fixnum, as pointed out in the post ruby and references. Working with fixnums, is that a Fixnum object lacks any methods that allow you to mutate the value.

Using a binding to solve the problem

I found the solution to my problem in the post ‘pass parameter by reference’ in Ruby?

Continue reading

Advertisements