Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'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) 
like image 284
Cristian Diaconescu Avatar asked Oct 02 '08 09:10

Cristian Diaconescu


People also ask

Can you pass by reference in Ruby?

Therefore Ruby does not use "pass by reference" in the C++ sense. If it did, then assigning a new object to a variable inside a function would cause the old object to be forgotten after the function returned.

Are arrays passed by reference in Ruby?

Ruby is not pass by reference.

How are the arguments in Ruby passed?

In ruby, arguments inside a method are passed by reference In ruby, we have a different situation, the variable that we have inside the method stores a reference to an object. Thus, if we will change an object inside the method, then it will be changed also outside the method.

What does it mean to pass a parameter by reference?

Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in. The following example shows how arguments are passed by reference.


1 Answers

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 
like image 126
jmah Avatar answered Sep 27 '22 20:09

jmah