Ruby - Number Argument Passing

Introduction

Ruby adheres to this principle: Arguments go into a method, any changes made inside the method cannot be accessed from the outside unless Ruby returns the changed value:

Demo

def hidden( aStr, anotherStr )
    anotherStr = aStr + " " + anotherStr
    return anotherStr.reverse
end# w  w  w .j  a v  a 2  s .c o m

str1 = "dlrow"
str2 = "olleh"
str3 = hidden(str1, str2)
puts( str1 )    #=> dlrow
puts( str2 )    #=> olleh
puts( str3 )    #=> hello world

Result

There are occasions that after arguments are passed to a Ruby method and changes made inside the method may affect variables outside the method.

This is because some Ruby methods modify the original object rather than yielding a value and assigning this to a new object.

For example, there are some methods ending with an exclamation mark that alter the original object.

The String append method << concatenates the string on its right to the string on its left but does not create a new string object.

If you use the << operator instead of the + operator in a method, your results will change:

def myBox( aStr, anotherStr )
    anotherStr = aStr << " " << anotherStr
    return anotherStr.reverse
end

str1 = "dlrow"
str2 = "olleh"
str3 = myBox(str1, str2)
puts( str1 )      #=> dlrow olleh
puts( str2 )      #=> olleh
puts( str3 )      #=> hello world