[Tip] When is Class#inherited called?

G

Gavin Kistner

(resend because the initial message didn't seem to get through)

I was wondering exactly when the #inherited method was called, and
(lacking documentation) did a quick investigation. The answer is "as
soon as the subclass begins being defined (the first time only) before
the first line of code in the definition".

(See that at the end, #inherited is not again when Foo::Bar is
re-opened.)

This is what I hoped, but not what I expected to find. Yay Ruby :)


p 'Before Foo'
class Foo
def self.inherited( k )
p "#{self}#inherited( #{k} )"
end

p "Inside #{self}, before Bar"
class Bar < self
p "Inside #{self}, before Jee"
class Jee < self;
p "Inside #{self}"
end
p "Inside #{self}, after Jee"
end
p "Inside #{self}, after Bar"
end
p 'After Foo'

class Foo2 < Foo
p "Inside #{self}"
end

class Foo::Bar < Foo
p "Re-opened #{self}"
end

#=> "Before Foo"
#=> "Inside Foo, before Bar"
#=> "Foo#inherited( Foo::Bar )"
#=> "Inside Foo::Bar, before Jee"
#=> "Foo::Bar#inherited( Foo::Bar::Jee )"
#=> "Inside Foo::Bar::Jee"
#=> "Inside Foo::Bar, after Jee"
#=> "Inside Foo, after Bar"
#=> "After Foo"
#=> "Foo#inherited( Foo2 )"
#=> "Inside Foo2"
#=> "Re-opened Foo::Bar"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top