Ruby 为什么要使用class<&书信电报;红宝石中的赛尔夫?

Ruby 为什么要使用class<&书信电报;红宝石中的赛尔夫?,ruby,Ruby,你能解释一下为什么开发人员使用class,因为他不知道这一点吗 def GeoPlanet::Base.build_url(resource_path, options = {}) end 这样也行吗 嗯,它们不是100%等价的:如果GeoPlanet不存在,那么原始代码片段将创建模块,但我的版本将引发namererror。要解决这个问题,您需要执行以下操作: module GeoPlanet def Base.build_url(resource_path, options = {})

你能解释一下为什么开发人员使用
class,因为他不知道这一点吗

def GeoPlanet::Base.build_url(resource_path, options = {}) end
这样也行吗

嗯,它们不是100%等价的:如果
GeoPlanet
不存在,那么原始代码片段将创建模块,但我的版本将引发
namererror
。要解决这个问题,您需要执行以下操作:

module GeoPlanet
  def Base.build_url(resource_path, options = {}) end
end
如果
Base
不存在,这当然会引发
namererror
。要解决这个问题,您需要:

module GeoPlanet
  class Base
    def self.build_url(resource_path, options = {}) end
  end
end

不管您怎么看,都不需要使用singleton类语法。有些人只是喜欢它。

我认为这只是风格/品味的问题。我喜欢使用
类Ok,所以GeoPlanet的例子有点古怪,对吧?你的两个例子更具可读性,我倾向于采用“self.build\uURL”的方式。
module GeoPlanet
  class Base
    def self.build_url(resource_path, options = {}) end
  end
end