0

In the minitest.rb file is inside the module Minitest the variable mc defined. What is this variable doing? I can't derive it from the context.

Here is a part of the code:

##
# :include: README.rdoc

module Minitest
  VERSION = "5.8.2" # :nodoc:
  ENCS = "".respond_to? :encoding # :nodoc:

  @@installed_at_exit ||= false
  @@after_run = []
  @extensions = []

  mc = (class << self; self; end)
Tobias
  • 4,523
  • 2
  • 20
  • 40
  • 3
    It's short for "metaclass". If `class << self; self; end` idiom says nothing to you, read a book called "Metaprogramming Ruby" – Sergio Tulentsev Nov 17 '15 at 10:38
  • I've read a few articles in the web and played around with the irb a little bit now. I think this style is a little bit strange at the beginning. But this is probably because I haven't worked with metaprogramming a lot before. – Tobias Nov 17 '15 at 10:50

1 Answers1

1

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.

Community
  • 1
  • 1
Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • Nice answer. Thank you! I've already bought the Metaprogramming Ruby Book and study it now. – Tobias Nov 17 '15 at 13:32