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)
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.
Ruby is not pass by reference.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With