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.
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 .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With