From: Gennady Bystritsky Date: 2010-04-02T17:09:42+09:00 Subject: Re: scope question On Apr 2, 2010, at 12:39 AM, Harry Kakueki wrote: > Maybe I'm missing something obvious here, but... I am afraid, you are. Hopefully not for long ;-) > Does this result surprise anyone else or just me? > I was expecting a_hash and an_arr to be local to the method. > Did I just do something stupid? > > > def scope_q(a_hash,an_arr,a_num) a_hash, an_arr and a_num are local to the method indeed. However, a_hash and an_array hold references to hash and array object respectively, not copies. So you are changing the objects passed to this method via those references. On the other hand, a_num is passed a Fixnum instance which are implemented as immediate objects and hence passed as copy. > a_hash["b"] = 3 > an_arr[1] = 5 > a_num += 1 > end > > h = {"a"=>1,"b"=>2,"c"=>3,"d"=>4} > a = [1,2,3,4] > n = 7 > > scope_q(h,a,n) Here where you pass references to Hash h and Array a, and n as an immediate object 7. > > p h #> {"a"=>1, "b"=>3, "c"=>3, "d"=>4} Changed in the method > p a #> [1, 5, 3, 4] Changed in the method > p n #> 7 Not changed as the methods incremented a copy. > > > #ruby 1.9.1p243 All ruby versions work identically in this area. > > > Harry >