【问题标题】:Ruby: class << self; def method VS. def self.method [duplicate]红宝石:类<<自我; def 方法 VS。 def self.method [重复]
【发布时间】:2014-04-15 17:19:28
【问题描述】:

我的理解是:

class Example
  class << self
    def my_method; end
  end
end

相当于:

class Example
  def self.my_method; end
end

但是这样对吗?

【问题讨论】:

  • 是的,没错:)
  • 一个重要(但很少需要)的区别是您可以使用class &lt;&lt; self 语法定义私有方法。
  • this 的可能副本,其中提出了一些有趣的观点。请注意,对于attr_accessor :a,您需要#1,对于类实例变量@a。您可以将class &lt;&lt; self 替换为instance_eval do

标签: ruby class


【解决方案1】:

它们是等价的,但为了清楚起见选择后者。当你有一个多行的类时,你可能会在使用class &lt;&lt; self 时错过类方法定义。

【讨论】:

    【解决方案2】:

    使用class &lt;&lt; self 的另一个好理由是当您需要类级别的访问器时:

    class Foo
      class << self
        attr_accessor :bar
      end
    end
    

    请注意,这通常不是您想要的,因为它不是线程安全的。但这是一个设计问题。如果你需要它,你需要它。

    【讨论】:

      【解决方案3】:

      在 class

      class Test
          def self.foo
          end
      
          def bar
          end
      end
      
      class Test
          class << self
              def foo
              end
          end
          def bar
          end 
      end
      

      在这两种情况下,您最终都会得到一个类方法“foo”和一个实例方法“bar”。两种方式都完成同样的事情。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-19
        • 1970-01-01
        • 1970-01-01
        • 2015-03-21
        • 1970-01-01
        • 2010-12-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多