From: "Jesús Gabriel y Galán" Date: 2010-04-02T18:19:54+09:00 Subject: Re: scope question On Fri, Apr 2, 2010 at 9:55 AM, Ryan Davis wrote: > > 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'. I would say that in order to explain this is more relevant to say that Fixnums are inmutable, rather that the fact that they are implemented as inmediate values. In his method he is not calling a mutating method on Fixnum, just assigning a new object to the local variable: def scope_q(a_hash,an_arr,a_num) a_num += 1 # this is equivalent to a_num = a_num + 1 end So my point is that, independently on the internal implementation of Fixnums, the important consideration for his question is the fact that they are inmutable, and so it's impossible to call a method that would modify the object. So it's not possible to mimic the same examples as with hashes and arrays. Jesus.