ruby - get name of class from class method
Remove .class
:
class A
def self.get_class_name
self.name.underscore.capitalize.constantize
end
end
self
in a context of a class (rather than the context of an instance method) refers to the class itself.
This is why you write def self.get_class_name
to define a class method. This means add method get_class_name
to self
(aka A
). It is equivalent to def A.get_class_method
.
It is also why when you tried self.class.name
you got Class
- the Object#class
of A
is Class
.
To make this clearer, consider the output of:
class A
puts "Outside: #{self}"
def self.some_class_method
puts "Inside class method: #{self}"
end
def some_instance_method
puts "Inside instance method: #{self}"
end
end
A.some_class_method
A.new.some_instance_method
Which is:
Outside: A
Inside class method: A
Inside instance method: #<A:0x218c8b0>