Search code examples
rubyparameter-passingpass-by-reference

'pass parameter by reference' in Ruby?


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)

Solution

  • 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