How do I determine the current open class in Ruby?
Classes in Ruby are first-class objects—each is an instance of class Class . Typically, you create a new class by using: class Name # some code describing the class behavior end. When a new class is created, an object of type Class is initialized and assigned to a global constant ( Name in this case).
What is a class in Ruby? Classes are the basic building blocks in Object-Oriented Programming (OOP) & they help you define a blueprint for creating objects. Objects are the products of the class.
The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module. Remember in Ruby, classes and methods may be considered constants too.
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'
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
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