I ran across an unexpected result when passing an array to a function and the behavior of <<
vs +=
.
Can anyone explain why the following
My understanding is that in Ruby all function arguments are passed by reference
No, as you have discovered yourself, Ruby is pass-by-value, not pass-by-reference. That's why you are seeing the result you are seeing.
The main difference between the #<<
, and #+
s that #<<
is just the Array
's instance method, so you just add a value to the specified instance of Array
arr = []
arr.__id__ # => 68916130
arr << 10
arr.__id__ # => 68916130
but in form of #+
is used assignment operator, which replace reference to a variable with a new instance, and that new instance shall not be passed into uplevel of the #add_to_array
function.
arr = []
arr.__id__ # => 68916130
arr += [10]
arr.__id__ # => 68725310
NOTE: That +=
implies the #+
method plus assignment operator =
, however ruby interpreter treats it as a specific operator not as a sum.
The form arr = arr + [10]
isn't work properly also.
def add_to_array(value, arr)
arr = arr + [value]
end
build_results()
# => []