From: Ryan Davis Date: 2010-04-02T16:55:01+09:00 Subject: Re: scope question On Apr 2, 2010, at 00:39 , Harry Kakueki wrote: > Maybe I'm missing something obvious here, but... > 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? nope. that's how it works. Every reference (variable, name, whatever you want to call it) to an object (with some exceptions) is a pointer to the actual object. When you call scope_q(h,a,n) you are passing those references into the method and they're modified directly. > def scope_q(a_hash,an_arr,a_num) > 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) > > p h #> {"a"=>1, "b"=>3, "c"=>3, "d"=>4} > p a #> [1, 5, 3, 4] > p n #> 7 The obvious counter-example is here with a_num/n. Small integers (fixnums) are optimized so they're not a pointer to a 32 bit number and are instead a 30 bit number (2 bits used for flags for special cases). so 7 gets copied in instead of passing a reference to it. As a result, the copy gets modified, not the original value at 'n'.