JP Richardson JP Richardson - 3 months ago 9
Ruby Question

Class Method to 'Know' Class Name in Ruby?

I want an inherited ruby class to 'know' its class name via a class method. This is best illustrated by a contrived example:

class Parent
def self.whoami
??
end
end

class Child < Parent
#No code should be needed.
end


So I should be able to call:

Parent.whomai


and expect a return of "Parent" I should then be able to call:

Child.whoami


and expect a return of "Child" I have a feeling that in conventional languages this might not be possible. But Ruby's metaprogramming model has amazed me before. Any thoughts? Thanks in advance.

Answer

A Class Method is a method where the CLASS is the receiver, so to find the object upon which the method is invoked (what you appear to be trying to do here) simply inspect the value of self.

class Parent
  def self.whoami
    self
  end
end

class Child < Parent
end

puts Parent.whoami #=> Parent
puts Child.whoami #=> Child