【问题标题】:class methods and different styles of programming in ruby [duplicate]ruby中的类方法和不同风格的编程[重复]
【发布时间】:2013-04-18 11:43:33
【问题描述】:

我很好奇调用类方法以及两者之间是否有任何区别:

class Jt
  class << self
    def say_hello
      puts "I want to say hello"
    end
  end
end

class Jt2
  def self.say_hello
    puts "2 want to say hello"
  end
end

Jt.say_hello
Jt2.say_hello

仅仅是样式还是 ruby​​ 处理这些的方式有什么不同?我总是将后者用于 Rails 的东西,但倾向于在元编程或 Rails 源代码中看到前者。

【问题讨论】:

  • 嗯...所以从我得到的用户角度来看,问题+答案似乎是how?(我认为)。我想我只是想知道它们在性能、资源等方面是否真的相当……以及出于非风格原因是否应该优先考虑其中一个。
  • @sawa 这个问题不是您链接到的另一个问题的副本。这个问题是问为什么“eigenclass”与“class”不同;这个问题不是在谈论定义方法的两种不同方式。
  • @DavidGrayson 你是对的。我链接到的问题是相关的,但不一样。

标签: ruby


【解决方案1】:
class << self
    def say_hello
      puts "I want to say hello"
    end
end
  • singleton class 内的class Jt

这里有更多信息What's the difference between a class and the singleton of that class in Ruby? 和看这里 Singleton class in Ruby

【讨论】:

    【解决方案2】:

    我认为它们之间的区别只是风格。他们都向类的单例类添加了一个方法。以下是我对您的代码所做的调查:

    class Jt
      class << self
        def say_hello
          puts "I want to say hello"
        end
      end
    end
    
    class Jt2
      def self.say_hello
        puts "2 want to say hello"
      end
    end
    
    p Jt.singleton_class.instance_method(:say_hello)   # => #<UnboundMethod: #<Class:Jt>#say_hello>
    p Jt2.singleton_class.instance_method(:say_hello)  # => #<UnboundMethod: #<Class:Jt2>#say_hello>
    

    以防万一,我使用了 JRuby。

    【讨论】:

    • 谢谢,我的直觉是你是对的,只是风格。刚开始了解 Ruby,很想​​看看是否存在 deeper 原因,因为类方法语法在用户空间应用程序中似乎无处不在,而 eigenclass 方法似乎在框架、库等中非常普遍......
    • 这不仅仅是风格。调用&lt;&lt; self 涉及更多步骤并使用更多资源。在&lt;&lt; self 中定义方法时,会在两个不同的地方定义相同的方法。您可以使用set_trace_func 注意到差异。
    • thx @sawa ,这似乎是合乎逻辑的,但它是编写库和框架的选择方式并不令人惊讶。不想争论,只是想理解。
    • @timpone 如果你关心资源,后一种方式更好。但是,您必须每次都重复self.。使用&lt;&lt; self 会(稍微多一点)资源消耗,但程序员不必重复self.。这就是为什么有些人会选择这种方式。
    • 感谢 David 和 @sawa 的输入。对这些在功能上是等效的感到更有信心。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 2016-04-25
    • 1970-01-01
    • 2013-07-07
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多