I'm curious about calling class methods and whether there is any difference between:
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
Is it just style or is there any difference in how ruby handle these? I always use the latter for Rails stuff but tend to see the former in meta-programming or Rails source code.
I think the difference between those is just style. They both add a method to the singleton class of the class. Here is what I did with your code to investigate it:
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>
In case it matters, I used JRuby.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With