DEV Community


Discussion on: Unraveling Classes, Instances and Metaclasses in Ruby

citizen428 profile image
Michael Kohl • Edited

You hinted at classes being instances themselves, but I guess it doesn't hurt to point out their actual class, which unsurprisingly is Class:

Foo =
#=> Foo
#=> Class
Bar =
#=> Bar
#=> Class
#=> Foo

Of course the class instances don't have to be assigned to constants, but it's customary as that's what the standard library does.

A global variable refers to the class object,

This is not correct. As mentioned above classes are assigned to constants and their visibility follows normal constant lookup rules (important for example in the case of nested classes). A class assinged to a global variable would look like this:

$omg_why =
#=> #<Class:0x0000000110cc2778>
defined? $omg_why
#=> "global-variable"
defined? Foo
#=> "constant"

Final comment: instead of instance_eval you can also use define_singleton_method, the analogue to define_method:

class User
  define_singleton_method :all do
    [new("Thijs"), new("Robert"), new("Tom")]

#=> [#<User:0x0000000110c63db8 @name="Thijs">, #<User:0x0000000110c63d68 @name="Robert">, #<User:0x0000000110c63d18 @name="Tom">]

Apart from saving a level of indentation it's also a proper closure, which can be useful if you're trying to capture some value.

jkreeftmeijer profile image
Jeff Kreeftmeijer Author

Hey Michael!

Thanks for your comments. You're right about those global variables, these were supposed to be constants instead. I've updated the article to reflect that.