From: Eric Christopherson Date: 2011-03-10T12:56:33+09:00 Subject: Re: basic programming question, help please On Mon, Mar 7, 2011 at 11:14 PM, Mayank Kohaley wrote: > On Tue, Mar 8, 2011 at 10:01 AM, Eric Christopherson < > echristopherson@gmail.com> wrote: > >> On Mon, Mar 7, 2011 at 5:31 PM, Gary Wright wrote: >> > >> > On Mar 7, 2011, at 7:03 AM, Mayank Kohaley wrote: >> > >> >> The class method in Ruby is represented using self. or >> > >> name>., A class method is used to modify the class >> variables( >> >> which has the same value in every object of that class, as you have in >> your >> >> program @@number_of_squares). >> > >> > This is only partially correct.  A class method is not 'used to modify >> > class variables'.  It can be used to do that but so can many other >> mechanisms >> > including code in an instance method, a block, or a module or class >> definition. >> > >> > It is misleading to say a class variable has 'the same value in every >> object >> > of the class' since it suggests that class variables are in some way >> associated >> > with instances (or 'self') but they aren't. They are associated with the >> innermost >> > lexical scope, which for most instance method definitions is just the >> class >> > definition block but that is more coincidence than design.  Consider the >> code >> > below where an instance method for A is defined within the lexical scope >> of B. >> > >> > class A >> >  @@a = "defined in A" >> > end >> > >> > class B >> >  @@a = "defined in B" >> >  A.send(:define_method, :show_a) { @@a } >> >  A.send(:define_method, :show_x) { @@x } >> > end >> > >> > class C < A >> > end >> > >> > A.new.show_a   #  "defined in B" >> > >> > class Object >> >  @@x = 'defined in Object' >> > end >> > A.new.show_x   # defined in Object" >> > >> > This shows that the resolution of class variables is based on the lexical >> > scope and not the dynamic scope. The method #show_x also shows that >> > the class hierarchy is also traversed when resolving a class variable >> (first B >> > is considered and then Object because B is a subclass of Object) >> >> Interestingly, if you put >> >> @@x = "defined in B" >> >> in class B, A.new.show_x still shows "defined in Object". >> >> > After putting @@x = "defined in B" in class B it shows "defined in B" and > not "defined in Object", and it makes sense as it works according to lexical > scope and not the dynamic scope. This is how I changed the class B without > changing anything else > > class B >  @@a = "defined in B" >  @@x = "defined in B" >  A.send(:define_method, :show_a) { puts @@a } >  A.send(:define_method, :show_x) { puts @@x } > end > Ohhh, fun. It turns out that Ruby 1.8 shows both as "defined in B", but Ruby 1.9 has show_x print "defined in Object".