From: Eric Christopherson Date: 2011-03-08T13:31:12+09:00 Subject: Re: basic programming question, help please 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".