Ruby method scope convention
- Ruby method not have a strict pass by value or pass by reference.
- if you passing an argument, and the argument calls a method that mutates the caller which may or may not have a
!
, then it’s going to change that object.
This is very common source bug.
example
pass by value(not mutate argument in method):
a = [1, 2, 1]
def my_method(a)
a.uniq
end
puts a
will produce:
1
2
1
pass by reference(mutate argument in method):
a = [1, 2, 1]
def my_method(a)
a.uniq!
end
puts a
will produce:
1
2