From: "Jesús Gabriel y Galán" Date: 2011-01-18T17:45:08+09:00 Subject: Re: Calling by Reference - Two Questions On Tue, Jan 18, 2011 at 8:47 AM, Mike Stephens wrote: > Interesting. > > I'm trying to see the pattern here. Ruby doesn't change arr's object if > it is refering to elements already present. However (I can only test > this in tryruby at this moment) it does change the object and therefore > lose the change if I do: > > def myswapx(arr) >  arr[2] = 3 > end > > So what's the rule? The rule is how Ruby handles variables and objects. A local variable holds a reference to an object. When you call a method passing that variable, the reference gets copied into a new local variable, that is only accessible in the method: def m variable_local_to_method_m end a = [1,2,3] m(a) Here, variable_local_to_method_m and a reference the same object, the array [1,2,3], but within the method you cannot make a reference a different object, because what gets passed to the method is a copy of the reference. If the object has mutable method, calling those methods through the variable_local_to_method_m will result in the object changing its state, which is obviously visible outside the method, when you access the object through variable a. For example: irb(main):001:0> class Item irb(main):002:1> def initialize irb(main):003:2> @count = 0 irb(main):004:2> end irb(main):005:1> def increment irb(main):006:2> @count += 1 irb(main):007:2> end irb(main):008:1> end => nil irb(main):009:0> def m item irb(main):010:1> item.increment irb(main):011:1> end => nil irb(main):012:0> a = Item.new => # irb(main):013:0> m a => 1 irb(main):014:0> a => # As you can see, when we call the increment method using the item variable inside the method m, the object changes its @count instance variable. Both item and a reference the same object, so after the method, a still references the same object which has a different state now. In your example the array [1,2,3] is the object whose reference is being passed to methods. An array is a mutable object, and so when you call a method like []= you are changing the object that is referenced by the outside variable a. Jesus.