Search code examples
rubyanonymous-class

Creating anonymous classes in ruby


According to the "well ground rubyist" in the example c "contains" or "points at" an anonymous class. Am I right, that C is not an anonymous class? That's really a little bit confusing.

    >> c = Class.new
    => #<Class:0x0000000006c4bd40>
    >> o1 = c.new
    => #<#<Class:0x0000000006c4bd40>:0x0000000006b81ec8>
    >> o1.class
    => #<Class:0x0000000006c4bd40>
    >>
    >> C = Class.new
    => C
    >> o2 = C.new
    => #<C:0x0000000006494480>
    >> o2.class
    => C

Solution

    • Class.new creates a new anonymous (unnamed) class

    • c = Class.new creates a new anonymous class and assigns it to the local variable c

    • C = Class.new creates a new anonymous class and assigns it to the constant C

    Although both assignments look almost identical, there's a subtle but important difference: assigning an anonymous class to a constant sets the name of that class to the name of the constant:

    c = Class.new
    c.name #=> nil
    
    C = Class.new
    C.name #=> "C"
    

    This is also mentioned in the docs for Class.new:

    You can give a class a name by assigning the class object to a constant.

    At this point, the class is no longer anonymous. It now has a name and we can refer to it using that name in the form of the constant C.