Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Variable passed to function gets changed

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?

like image 345
Peter-W Avatar asked Aug 10 '26 05:08

Peter-W


1 Answers

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
like image 96
Stefan Avatar answered Aug 12 '26 07:08

Stefan