You will need Class#ancestors
:
Camel.ancestors #=> [Camel, Mammal, Animal, Object, Kernel, BasicObject]
You will get more classes than you defined, so you need to stop at Object
:
class Animal def to_s "I am a " + self.class.ancestors.take_while{|klass| klass != Object}.join(' and a ') end end class Mammal < Animal end class Camel < Mammal end puts Animal.new
ancestors
can be modules or classes, so if you just want Classes, you can use:
def to_s "I am a " + self.class.ancestors.take_while{|klass| klass < Object}.join(' and a ') end
So, is there a keyword, method, or something that allows you to access the containing class?
I could not find him. Adding
puts method(__method__).owner
until Animal#to_s
or Mammal#to_s
still returns Camel
.
source share