您能解释一下开发人员为什么使用 class << self
吗?向基类添加方法?
base.rb from the GeoPlanet Gem
module GeoPlanet
class Base
class << self
def build_url(resource_path, options = {})
end
end
end
最佳答案
因为他不知道
def GeoPlanet::Base.build_url(resource_path, options = {}) end
也可以吗?
嗯,它们不是 100% 等价的:如果 GeoPlanet
不存在,那么原始代码片段将创建模块,但我的版本将引发 NameError
.要解决这个问题,您需要这样做:
module GeoPlanet
def Base.build_url(resource_path, options = {}) end
end
如果 Base
不存在,这当然会引发 NameError
。要解决这个问题,,您可以:
module GeoPlanet
class Base
def self.build_url(resource_path, options = {}) end
end
end
无论您怎么看,都需要使用单例类语法。有些人只是喜欢它。
关于ruby - 为什么在 ruby 中使用 class << self?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4054270/