Hi --

On Fri, 17 Nov 2006, Xavier Noria wrote:

> On Nov 16, 2006, at 1:01 PM, dblack / wobblini.net wrote:
>
>>  class C
>>    class << self
>>      attr_accessor :x
>>    end
>>  end
>> 
>> Now, the class object C has an attribute "x":
>>
>>  C.x = 1
>>  puts C.new.class.x   # 1
>
> David, technically is there any relationship between the attribute @x here
>
> class A
>   @x = 1
> end
>
> and the @x that accessor deals with?

Yes; they're the same @x.

> That would be an attribute of what? Is there a singleton instance of
> the singleton class?  Or is that @x an attribute of A as instance of
> Class? I tried to get this right with examples but I guess the exact
> answer comes from the actual implementation.

@x is an instance variable of A.  The accessor methods are defined for
A only, not for all classes.  In general, when you do this:

   class << obj
     ...
   end

you're in the singleton class of obj, and whatever instance methods
you define are singleton methods of obj.  attr_accessor is just a
mechanism for writing instance methods.  So what I did was equivalent
to:

   class A
     class << self
       def x
         @x
       end
       def x=(y)
         @x = y
       end
     end
   end

i.e., adding instance methods to A's singleton class.


David

-- 
                   David A. Black | dblack / rubypal.com
Author of "Ruby for Rails"   [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB's Weblog)        [2] | Co-director, Ruby Central, Inc.   [4]
[1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com    | [4] http://www.rubycentral.org