Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class methods and different styles of programming in ruby [duplicate]

Tags:

ruby

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.

like image 732
timpone Avatar asked Aug 13 '26 22:08

timpone


1 Answers

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.

like image 128
David Grayson Avatar answered Aug 16 '26 20:08

David Grayson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!