Minitest中的mc变量名是什么意思?
What does the mc variable name in Minitest mean?
在minitest.rb文件里面是模块Minitest
里面的变量mc
定义的。这个变量在做什么?我无法从上下文中得出它。
这是部分代码:
##
# :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)
回到过去,在我们有 Object#singleton_class
方法之前,访问单例 class 的唯一方法是打开单例 class 和 return self
来自 class 定义表达式。
请记住,class 定义表达式与所有其他定义表达式一样,计算结果为定义中最后计算的表达式的值,例如:
class Foo
42
end
# => 42
还请记住,在 class 定义表达式中,特殊变量 self
的值是 class 对象本身:
class Bar
self
end
# => Bar
最后但同样重要的是,请记住 class << some_expression
打开 some_expression
计算结果的任何对象的单例 class。
综合起来:
class << self # Here, self is Minitest
self # Here, self is the singleton class of Minitest
end
打开self
的单例class,也就是Minitest
模块本身,然后returns self
从单例class 定义,即 class 本身,因此 Minitest
.
的单例 class
至于为什么变量被命名为mc
:这是"metaclass"的缩写,这是我们现在称为单例的少数几个名称之一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 与 Ruby.
中的单例 class 不完全匹配
如今,我们可能只是直接调用 singleton_class
,或者,如果我们出于性能原因想要对其进行缓存,则执行类似
的操作
sc = singleton_class
相反。
在minitest.rb文件里面是模块Minitest
里面的变量mc
定义的。这个变量在做什么?我无法从上下文中得出它。
这是部分代码:
##
# :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)
回到过去,在我们有 Object#singleton_class
方法之前,访问单例 class 的唯一方法是打开单例 class 和 return self
来自 class 定义表达式。
请记住,class 定义表达式与所有其他定义表达式一样,计算结果为定义中最后计算的表达式的值,例如:
class Foo
42
end
# => 42
还请记住,在 class 定义表达式中,特殊变量 self
的值是 class 对象本身:
class Bar
self
end
# => Bar
最后但同样重要的是,请记住 class << some_expression
打开 some_expression
计算结果的任何对象的单例 class。
综合起来:
class << self # Here, self is Minitest
self # Here, self is the singleton class of Minitest
end
打开self
的单例class,也就是Minitest
模块本身,然后returns self
从单例class 定义,即 class 本身,因此 Minitest
.
至于为什么变量被命名为mc
:这是"metaclass"的缩写,这是我们现在称为单例的少数几个名称之一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 与 Ruby.
如今,我们可能只是直接调用 singleton_class
,或者,如果我们出于性能原因想要对其进行缓存,则执行类似
sc = singleton_class
相反。