Ruby - By Reference or By Value?


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


def aMethod( anArg )
    puts( "#{anArg.object_id}\n\n" )
end# w ww .j  a va2s. co  m

class MyClass

i = 10
f = 10.5
s = "hello world"
ob =

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 )


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:


num = 11.5
num2 = 11.5#  w ww .j a  v  a 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


Related Topic