代码之家  ›  专栏  ›  技术社区  ›  jspooner Ryan Bigg

为什么在Ruby中使用class<<self?

  •  4
  • jspooner Ryan Bigg  · 技术社区  · 16 年前

    你能解释一下为什么开发者使用 class << self 要向基类添加方法吗?

    base.rb from the GeoPlanet Gem

    module GeoPlanet
      class Base
        class << self
          def build_url(resource_path, options = {})
        end
      end
    end
    
    2 回复  |  直到 16 年前
        1
  •  9
  •   Jörg W Mittag    16 年前

    因为他不知道

    def GeoPlanet::Base.build_url(resource_path, options = {}) end
    

    也可以吗?

    嗯,它们不是100%等价的:如果 GeoPlanet 不存在,则原始代码段将创建模块,但我的版本将引发 NameError . 为了解决这个问题,你需要这样做:

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

    那当然会提高 命名错误 如果 Base 不存在。四处工作 那个 你应该这样做:

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

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

        2
  •  6
  •   Brian    16 年前

    我认为这只是风格/品味的问题。我喜欢用 class << self 当我有很多类方法要组合在一起或提供与实例方法的某种视觉分离时,使用此方法。

    如果我所有的方法都是类方法的话,我也会使用这种方法,就像地质计划的作者那样。

    推荐文章