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

前端 未结 2 1560
北荒
北荒 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: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()
    # => [] 
    

提交回复
热议问题