Why is the variable var passed to a function in the following code changed after the function has been executed?
def my_func(my_var)
out_var = my_var
out_var[3]="STUFF"
return out_var
end
var = "Testing"
puts my_func(var)
puts var
Output:
TesSTUFFing
TesSTUFFing
Why has "var" been changed? Can someone please explain this to me?
In Ruby variables are passed by reference.
You have to explicitly clone the variable:
def my_func(my_var)
out_var = my_var.clone
out_var[3]="STUFF"
out_var
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With