Ruby array manipulation inside method

  • A+

I just stumbled upon a concept I don't understand. What is the explanation behind this? What theory am I missing?

def method_1(a)     a << "new value" end  input_1 = [] method_1(input_1) print input_1 # ["new value"]  def method_2(a)     a = ["new value"] end  input_2 = [] method_2(input_2) print input_2 # [] 

Why input_1 changes whereas input_2 doesn't change?


With a bit of simplification we can say that a variable in Ruby is a reference to a value. In your case variable a holds a reference to an array.

a << (a.append) mutates the value stored in variable a. The reference is not changed, but the value did. It's the case of method_1

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

Assignment = changes the reference stored in a variable - it starts to point to a different value. References are copied when passed to a method. Because of that when you call

def method_2(a)     a = ["new value"] end input = [] method_2(a) 

You only change a reference stored in a that is local to the method, without any change to the reference stored in input nor to the value (and array of []) that is pointed by this reference.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: