See "Is Ruby pass by reference or by value?" on how Ruby handles arguments.
Generally speaking, you can pass an object to a method, modify the object attributes within that method and the modifications will still be there after the method returns.
What happens in your example though is shadowing of the parameter str
by the local variable str
. Since you make an assignment to the local variable and not to the passed argument, the modification is lost as soon as the method returns and its local scope is destroyed.
Your options are either return a value from the method and use it outside like this:
def my_method(str)
str + 'salut' # a new instance of string is created and returned
end
str = 'hey, '
str = my_method(str)
puts str # outputs 'hey, salut'
or use a mutator method such as #replace
def my_method(str)
str.replace('salut') # same string instance is reused
end
str = 'whatever'
my_method(str)
puts str # outputs 'salut'
You can handle easily handle passed arrays inside a method by changing values using index like so:
def my_method(array)
array[15] = 10
end
Or add items via <<
:
def my_method(array)
array << 10
end
Or call its methods like this:
def my_method(array)
array.delete(0)
end
All these modifications will be kept since the outer scope holds the reference to the same array instance you're operating on within the method.