我很好奇调用类方法和它们之间是否有任何区别:
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 源代码中看到前者。
我认为它们之间的区别只是风格。他们都在类的单例类中添加了一个方法。以下是我对您的代码所做的调查:
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。