这个Ruby Style Guide指出,最好使用self.method_name
而不是class method_name
。但为什么呢?
class TestClass
# bad
class << self
def first_method
# body omitted
end
def second_method_etc
# body omitted
end
end
# good
def self.first_method
# body omitted
end
def self.second_method_etc
# body omitted
end
end
有性能问题吗?
self
更易读。此外,这也是一种标准(我从未见过使用class <<
的 gem/app 等)。 - Samy Dindaneclass << self
,不要说元类或特别是不要说 Eigenclass。这些都是令人困惑、过时的名称,Ruby有一个适当的名称来代替它们:单例类。可以使用singleton_class.class_eval
代替class << self
,这样更清晰地表达了正在发生的事情。对于单个方法,可以使用define_singleton_method
,这更加明确。 - Max