Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 210
JP Richardson Avatar asked Nov 13 '10 06:11

JP Richardson


People also ask

How do I find the class in Ruby?

There are multiple ways we can check the name of a class in Ruby. One way using object.class.name , another way using object. class. to_s .

What is a class method in Ruby?

Class Methods are the methods that are defined inside the class, public class methods can be accessed with the help of objects. The method is marked as private by default, when a method is defined outside of the class definition. By default, methods are marked as public which is defined in the class definition.

Can we call methods using class name?

Yes, It is allowed to define a method with the same name as that of a class. There is no compile-time or runtime error will occur.


1 Answers

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
like image 84
horseyguy Avatar answered Oct 13 '22 11:10

horseyguy