'pass parameter by reference' in Ruby?

Cristian Diaconescu picture Cristian Diaconescu · Oct 2, 2008 · Viewed 23.4k times · Source

In Ruby, is it possible to pass by reference a parameter with value-type semantics (e.g. a Fixnum)? I'm looking for something similar to C#'s 'ref' keyword.

Example:

def func(x) 
    x += 1
end

a = 5
func(a)  #this should be something like func(ref a)
puts a   #should read '6'

Btw. I know I could just use:

a = func(a)

Answer

jmah picture jmah · Oct 2, 2008

You can accomplish this by explicitly passing in the current binding:

def func(x, bdg)
  eval "#{x} += 1", bdg
end

a = 5
func(:a, binding)
puts a # => 6