Way back in the old days, before we had the Object#singleton_class
method, the only way to get access to the singleton class was to open up the singleton class and return self
from the class definition expression.
Remember, a class definition expression, like all other definition expressions, evaluates to the value of the last expression evaluated inside the definition, e.g.:
class Foo
42
end
# => 42
Remember also that inside a class definition expression, the value of the special variable self
is the class object itself:
class Bar
self
end
# => Bar
And last but not least, remember that class << some_expression
opens up the singleton class of whatever object some_expression
evaluates to.
Putting it all together:
class << self # Here, self is Minitest
self # Here, self is the singleton class of Minitest
end
Opens up the singleton class of self
, which is the Minitest
module itself, then it returns self
from the singleton class definition, which is the class itself, ergo the singleton class of Minitest
.
As to why the variable is named mc
: that's short for "metaclass", which is one of the few dozen names that were proposed for what we now call the singleton class. (Some of the other suggestions were eigenclass (my personal favorite), shadow class, virtual class (yuck!), ghost class, own class, …) It's a bit of an unfortunate name, because the term metaclass has a well-defined meaning that does not fully match what a singleton class is in Ruby.
Nowadays, we would probably just call singleton_class
directly, or, if we want to cache it for performance reasons, do something like
sc = singleton_class
instead.