DEV Community

loading...

Discussion on: Unraveling Classes, Instances and Metaclasses in Ruby

Collapse
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 = Class.new
#=> Foo
Foo.class
#=> Class
Bar = Class.new(Foo)
#=> Bar
Bar.class
#=> Class
Bar.superclass
#=> 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.new
#=> #<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")]
  end
end

User.all
#=> [#<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.

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