Ruby - By Reference or By Value?

Introduction

A by value argument is a copy of the original variable. You can pass it to a function, and the value of the original variable remains unchanged.

A by reference argument, on the other hand, is a pointer to the original variable. When this gets passed to a procedure, you pass a reference to the bit of memory in which the original data is stored. Any changes made inside the procedure are made to the original data and necessarily affect the value of the original variable.

For Ruby, you can verify it by object_id

Demo

def aMethod( anArg )
    puts( "#{anArg.object_id}\n\n" )
end#   w  w  w. j  ava 2 s.c  om

class MyClass
end

i = 10
f = 10.5
s = "hello world"
ob = MyClass.new

puts( "#{i}.object_id = #{i.object_id}" )
aMethod( i )
puts( "#{f}.object_id = #{f.object_id}" )
aMethod( f )
puts( "#{s}.object_id = #{s.object_id}" )
aMethod( s )
puts( "#{ob}.object_id = #{ob.object_id}" )
aMethod( ob )

Result

Simple Ruby assignment of one variable to another does not create a new object.

Suppose you have one variable called num and another called num2.

If you assign num2 to num, both variables will refer to the same object.

You can test this using the equal? method of the Object class:

Demo

num = 11.5
num2 = 11.5# from  ww  w . j a v  a  2s  .  co  m

# num and num 2 are not equal
puts( "#{num.equal?(num2)}" )    #=> false

num = num2
# but now they are equal
puts( "#{num.equal?(num2)}" )    #=> true

Result

Related Topic