2

What is difference between these two methods in Ruby?

class Mod   

      def doc(str)
          ...
      end

      def Mod::doc(aClass) 
          ...
      end
end
Messi
  • 97
  • 7
  • 3
    The latter looks like a class method to me. I'd write `def self.doc ...`, though – John Dvorak Mar 16 '16 at 04:14
  • Thanx for your reply. – Messi Mar 16 '16 at 04:22
  • Note that `Mod.instance_methods(false) #=> [:doc]` (the first) and `Mod.methods(false) #=> [:doc]` (the second). It's curious that `instance_methods` is the name of the first method (which more commonly is invoked on a class), even though instance methods can only be invoked on instances of classes which `include` the module (but, as @JörgWMittag is fond of pointing out (sic), "there are no instance methods, just methods"). – Cary Swoveland Mar 16 '16 at 05:19

1 Answers1

6
Mod::doc()

is a class method, whereas

doc()

is an instance method. Here's an example of how to use both:

class Mod   
    def doc()
        puts 1
    end

    def Mod::doc() 
        puts 2
    end
end

a = Mod.new
a.doc   #=> 1
Mod.doc #=> 2

Here's a question that compares it with

self.doc()
Community
  • 1
  • 1
SlySherZ
  • 1,631
  • 1
  • 16
  • 25