Ruby Pass by Value or Reference

Ruby pass by value or reference, which one of them is used when object/variables are passed to the functions. This tutorial will help you understand how passing value/objects in Ruby work.

Pass by Value:

def test_ruby_function(number)
   number = 54
   puts "Number is:#{number}"

number = 101
# call to method passing number variable
# Number is:54
# let us print value of number after execution of the function that tries to modify value of the variable 'number'.
puts "Number:#{number}"

Let us see the interpretation of this example below,

  1. The value of variable number is not modified by the function test_ruby_function.

  2. The function test_ruby_function does not have separate copy of ‘number’ object.

  3. The value of reference of object holding ‘number’ is sent to the function test_ruby_function

Yes, Ruby methods use Pass by Value, and not Pass by Reference - But, value of the reference of object is passed to the Ruby Methods

Passign value of a reference:

Example -

def sample_function(str)
   puts "Object ID of str:#{str.object_id}"
   str = 'Changed String'
   puts "Object ID of str:#{str.object_id}"

name = 'Ruby in Rails'
puts sample_function(name)
Object ID of str:70146988475640
Object ID of str:70146988429860

puts "Name is #{name}"
Name is Ruby in Rails
puts "Object ID of original name string:#{name.object_id}"
Object ID of original name string:70146988475640
  • It shows that original name string points to the same object even after the function call sample_function which tries to modify the value of the name.
  • When we try to assign new value to the variable passed to function, it changes reference to new memory location. Thus, old reference and it’s value are remained intact.
  • Thus, when we pass values to ruby function - we can change value of the variable keeping the same reference to the object. But when we can not replace it entirely by a new object.
  1. Mostly, Ruby uses pass by value. But, ruby passes value of reference of the object that needs to be shared between the function.
  2. Ultimately, ruby uses pass by object sharing.

If you are still not clear how passing variables are shared amongst functions in Ruby or what is Ruby Pass by value/ Pass by Reference then you can refer this StackOverflow answer for more information.

You can let us know through comments if you have any feedback/difficulty understanding this.