我的理解是:
class Example
class << self
def my_method; end
end
end
相当于:
class Example
def self.my_method; end
end
但这是正确的吗?
它们是等价的,但出于清晰的原因选择后者。如果您的类有很多行长,那么在使用class << self
时可能会错过类方法定义。
使用class << self
的另一个好理由是当您需要类级别的访问者时:
class Foo
class << self
attr_accessor :bar
end
end
注意,这通常不是你想要的,因为它不是线程安全的。但这是一个设计问题。如果你需要它,你就需要它。
在类<lt;self-all方法将是类方法,直到类<lt;自我是封闭的。对于一个单一级别或多个级别的类方法,如果你愿意,你可以将该方法定义为self.foo.
class Test
def self.foo
end
def bar
end
end
class Test
class << self
def foo
end
end
def bar
end
end
在这两种情况下,您最终都会得到一个类方法"foo"和一个实例方法"bar"。两种方法都能达到相同的效果。