Victor Schubert’s personal page

Ruby class names and assignment

In general each Ruby class has a name. It can be obtained by calling Class#name. There is an exception to this however: anonymous classes. The simplest way to create an anonymous class is through the constructor Class.new. As could be expected, anonymous classes’ name is nil. This name however can’t be directly assigned: there is no Class#name=. I was surprised to learn however, that there is still a mechanism through which a name can be assigned to an anonymous class. Assigning an anonymous class to a constant will assign the constant’s name as the class name.

irb(main):001:0> my_class = Class.new
=> #<Class:0x0000561172d87b40>
irb(main):002:0> my_class.name
=> nil
irb(main):003:0> MyClass = my_class
=> MyClass
irb(main):004:0> my_class.name
=> MyClass