From time to time, Ruby beginner articles can be found as if the class is a constant. this is,
class Hoge
end
p defined? Hoge # => "constant"
I think it comes from that.
If you write a constant name after defined?
, the specification returns the string " constant "
, but since that is the case, you can see that Hoge
is a constant.
Well, in the above example
Hoge
is a classHoge
is a constantIt ’s correct, but
It would be strange to say that. Because a class is an object, and a constant is an object.
So what exactly does that mean? It is like this.
class Hoge
end
When you execute the class definition expression, a class named " Hoge
"is defined, and it is assigned to a constant with the same name.
So Hoge
is the name of the class and the name of the constant that points to it.
The class itself is by no means a constant.
class Hoge
end
#Show class name
p Hoge.name # => "Hoge"
#Confirm that the constant with the same name is defined in Object by defining the class
p Object.constants.include?(:Hoge) # => true
So what happens if you define an anonymous class?
You can create an unnamed class with Class.new
.
c = Class.new
# (1)Make sure you don't have a name
p c.name # => nil
# (2)Substitute for some constant
Hoge = c
# (3)I have a name!
p c.name # => "Hoge"
# (4)Substitute for another constant
Fuga = c
# (5)The name does not change
p c.name # => "Hoge"
When you ask for the name of an unnamed class (at (3)), it looks for the constant to which it is assigned, and if found, uses that constant name as its name. You can name it at (3), not at (2).
I assigned it to another constant in (4), but since the class already has a name, it is not affected by (4) in (5).
If the name is assigned to multiple constants when the name is first obtained, it is uncertain which constant name will be used as the class name. Reference: Class.new (Ruby 3.0.0 Reference Manual)
Recommended Posts