When passing a Ruby array as an argument, why does `<<` append while `+=` does not?

前端 未结 2 1559
北荒
北荒 2021-01-24 14:48

I ran across an unexpected result when passing an array to a function and the behavior of << vs +=.

Can anyone explain why the following

相关标签:
2条回答
  • 2021-01-24 15:13

    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.

    0 讨论(0)
  • 2021-01-24 15:17

    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.

    Additionals

    The form arr = arr + [10] isn't work properly also.

    def add_to_array(value, arr)
      arr = arr + [value]
    end
    build_results()
    # => [] 
    
    0 讨论(0)
提交回复
热议问题