Ruby current class
Inside the class itself:
class_name = self.class
On an initialized object named obj
:
class_name = obj.class
if you have obj = SomeClass.new
you get the class with obj.class
Inside of a class
definition body, self
refers to the class itself. Module#name
will tell you the name of the class/module, but only if it actually has one. (In Ruby, there is no such thing as a "class name". Classes are simply objects just like any other which get assigned to variables just like any other. It's just that if you happen to assign a class object to a constant, then the name
method will return the name of that constant.)
Example:
puts class Foo
name
end
# Foo
But:
bar = Class.new
bar.name # => nil
BAR = bar
bar.name #=> 'BAR'