Reputation: 17577
How do I determine the current open class in Ruby?
Upvotes: 31
Views: 23884
Reputation: 7068
If you're looking to compare via the class name (string):
class Foo
def my_class_name_is
self.class.name
end
end
Foo.new.my_class_name_is
=> "Foo"
Upvotes: 2
Reputation: 6115
In my case, the name
method was overwrote, I find to_s
give me this same result
class Foo
puts self.name
puts self.to_s
end
#=> Foo
#=> Foo
Upvotes: 0
Reputation: 65944
Inside the class itself:
class_name = self.class
On an initialized object named obj
:
class_name = obj.class
Upvotes: 32
Reputation: 369438
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'
Upvotes: 29