Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 431
Eric Avatar asked Jul 01 '26 20:07

Eric


1 Answers

  • 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.

like image 127
Stefan Avatar answered Jul 04 '26 03:07

Stefan