Robert Klemme
9/24/2008 6:33:00 AM
On 24.09.2008 07:55, Ittay Dror wrote:
> Hi,
>
> I'll start with what I understand:
> class Foo
> class << self
> def hi
> puts 'HI'
> end
> end
> end
>
> Creates an instance of a singleton class that has the method #hi. So
> Foo.hi calls the method defined in the class of Foo -> the singleton
> class (which inherits from Class)
>
> My question:
> class Bar < Foo
> end
>
> Bar.hi --> 'HI'
>
> It looks like two things are happening: 1. Bar points to Foo, so
> instances of Bar lookup methods in Foo also. 2. The instance Bar has a
> class that inherits from Foo's instance class.
>
> Is this correct?
Basically yes. Although singleton classes are a bit tricky - they are
partly hidden (for example, you do not see them via Module#ancestors).
> Is there somewhere where I can find the exact flow of
> '<' (and '<<')?
AFAIK you cannot really "see" this:
irb(main):001:0> class Foo; end
=> nil
irb(main):002:0> class Bar < Foo; end
=> nil
irb(main):003:0> $fc = class <<Foo; self end
=> #<Class:Foo>
irb(main):004:0> $bc = class <<Bar; self end
=> #<Class:Bar>
irb(main):005:0> $bc < $fc
=> nil
irb(main):006:0> $bc > $fc
=> false
irb(main):007:0> $bc.ancestors
=> [Class, Module, Object, PP::ObjectMixin, Kernel]
irb(main):008:0> $fc.ancestors
=> [Class, Module, Object, PP::ObjectMixin, Kernel]
irb(main):009:0> Foo < $fc
=> nil
irb(main):011:0> $fc.superclass
=> #<Class:Class>
irb(main):012:0> $bc.superclass
=> #<Class:Class>
I keep remembering that instance methods of a singleton class are
inherited by singleton classes of subclasses. This has served me well
in the past. :-)
Cheers
robert