我很想知道调用类方法以及它们之间是否有任何区别:
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源代码中看到前者。
答案 0 :(得分:1)
我认为这些之间的区别只是风格。它们都为类的singleton类添加了一个方法。以下是我对您的代码进行调查所做的事情:
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。
答案 1 :(得分: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