Ruby array manipulation inside method

后端 未结 3 1849
傲寒
傲寒 2021-01-19 01:05

In the following, input_1 changes:

def method_1(a)
  a << \"new value\"
end

input_1 = []
method_1(input_1)
input_1 #=> [\"new value\"]         


        
3条回答
  •  無奈伤痛
    2021-01-19 01:43

    It boils down to Ruby using "pass-reference-by-value".

    The exact case that you encounter is described in this excellent blog post.

    The gist:

    In method_1 you are changing the value of an object that two different variables (input_1 and a) are both pointing to.

    In method_2 you are reassigning a completely new object to one of the two variables (a).

提交回复
热议问题