3

クラスメソッドの呼び出しと、次の違いがあるかどうかに興味があります。

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

それは単なるスタイルですか、それともルビーがこれらを処理する方法に違いはありますか? 私は常に後者を Rails のものに使用しますが、メタプログラミングや Rails のソース コードでは前者をよく見かけます。

4

2 に答える 2

1

それらの違いはただのスタイルだと思います。どちらも、クラスのシングルトン クラスにメソッドを追加します。これを調査するためにあなたのコードで行ったことは次のとおりです。

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 を使用しました。

于 2013-04-24T19:25:33.760 に答える
0
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

于 2013-04-24T19:09:54.520 に答える