On 8/14/10, Chan Nguyen <cnguyen / rapattoni.com> wrote:
> Hi everyone,
> In C++, in order to modify a variable being passed into a function we do
> [code]
> void func( int& x )
> {
>     x = 10;
> }
> [/code]
>
> I wonder is there a way to do something like this in Ruby or a similar
> idea? If there's no reference type then how would we be able to modify a
> varible?

On the (rare) occasions when I have needed this, I make the parameter
an array containing a single value instead. Your c++ code could
translate to ruby as this:

def func(x_array)
  x_array[0]=10
end

#call it like this:
var=[9]
func(var)
p var[0]   #=>10

This is basically what c++ does with reference parameters under the
surface anyway. This is more awkward in ruby, since you have to
explicitly dereference your array in the method and afterwards to get
the changed value. The awkwardness is only a minor annoyance and
should serve as a reminder to you to find another way to do it. The
other answers in this thread offer some good advice.