Hi --

On Fri, 9 May 2003, Jim Freeze wrote:

> On Friday,  9 May 2003 at 16:18:43 +0900, Mauricio Fern?ndez wrote:
> > On Fri, May 09, 2003 at 01:13:51PM +0900, Jim Freeze wrote:
> > > So, fundamentally, is the code in both class C and D below
> > > doing the same thing?
> > >
> > > class C
> > >   class << self
> > >     def set(x); @x = x; end
> > >     def get; puts @x; end
> > >   end
> > > end
> > >
> > > class D
> > >   def self.set; @x = x; end
> > >   def self.get; puts @x; end
> > > end
> >
> > > If these class methods have instance variables for the
> > > singleton object, are class methods not just really
> > > instance methods of the singleton object?
> >
> > I don't think "singleton object" is standard terminology here.
> > Regardless of the use of class instance variables, class methods are in
> > fact singleton methods of the object that represents the class (i.e.,
> > that of type Class). You can also view them as instance methods of the
> > associated *singleton class*.
> >
>
> Hmm, associated singleton class seems weird to me.
> Why does an object (in this case a class object)
> have an associated singleton class? Don't objects
> just have single methods added to them?

Yes, but there's a specific mechanism for that: the method is actually
added to the object's singleton class.  Compare these two scenarios:

# Scenario one: add a method to a regular (non-singleton) class:

  str = "Hello"
  class String
    def some_new_method
      puts "I'm a new method!"
    end
  end

  str.some_new_method               # I'm a new method!
  "other string".some_new_method    # I'm a new method!


# Scenario two: add a method to a singleton class:

  str = "Hello"
  class << str
    def some_new_method
      puts "I'm a new method!"
    end
  end

  str.some_new_method               # I'm a new method!
  "other string".some_new_method    # error -- no such method


In both cases, an instance method is being added to a class.  The only
difference is that in #1 the class is String, which is a non-singleton
class and can have many instances, whereas in #2 the class is "the
singleton class of str" (it's an anonymous class).  By definition, the
singleton class of str can have only one instance: str.  Other String
objects don't have the methods added to str's singleton class.

When we do it this way:

  str = "Hello"
  def str.some_new_method
    puts "I'm a new method"
  end

the feeling of "adding the method to the object" is more palpable, but
the method is in fact being defined as an instance method of str's
singleton class.  And of course that "add to the object" syntax is the
most common for singleton methods of Class objects (i.e., "class
methods").


David

-- 
David Alan Black
home: dblack / superlink.net
work: blackdav / shu.edu
Web:  http://pirate.shu.edu/~blackdav