On Mon, Mar 7, 2011 at 11:14 PM, Mayank Kohaley
<mayank.kohaley / gmail.com> 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 <gwtmp01 / mac.com> wrote:
>> >
>> > On Mar 7, 2011, at 7:03 AM, Mayank Kohaley wrote:
>> >
>> >> The class method in Ruby is represented using self.<method name> or
>> <class
>> >> name>.<method 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 i=
n
>> your
>> >> program @@number_of_squares).
>> >
>> > This is only partially correct. =A0A class method is not 'used to modi=
fy
>> > class variables'. =A0It 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 t=
he
>> innermost
>> > lexical scope, which for most instance method definitions is just the
>> class
>> > definition block but that is more coincidence than design. =A0Consider=
 the
>> code
>> > below where an instance method for A is defined within the lexical sco=
pe
>> of B.
>> >
>> > class A
>> > =A0@@a =3D "defined in A"
>> > end
>> >
>> > class B
>> > =A0@@a =3D "defined in B"
>> > =A0A.send(:define_method, :show_a) { @@a }
>> > =A0A.send(:define_method, :show_x) { @@x }
>> > end
>> >
>> > class C < A
>> > end
>> >
>> > A.new.show_a =A0 # =A0"defined in B"
>> >
>> > class Object
>> > =A0@@x =3D 'defined in Object'
>> > end
>> > A.new.show_x =A0 # defined in Object"
>> >
>> > This shows that the resolution of class variables is based on the lexi=
cal
>> > 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 =3D "defined in B"
>>
>> in class B, A.new.show_x still shows "defined in Object".
>>
>>
> After putting @@x =3D "defined in B" in class B it shows "defined in B" a=
nd
> not "defined in Object", and it makes sense as it works according to lexi=
cal
> scope and not the dynamic scope. This is how I changed the class B withou=
t
> changing anything else
>
> class B
> =A0@@a =3D "defined in B"
> =A0@@x =3D "defined in B"
> =A0A.send(:define_method, :show_a) { puts @@a }
> =A0A.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".