4

I'm doing the following Ruby Tutorial http://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/48-advanced-modules/lessons/118-wrapping-up-modules

One of the exercises asks me to

...define a static method square in the module Math. It should obviously return the square of the number passed to it...

Why does it only work when I prefix the method definition with "self"? E.g. the following works:

module Math
  def self.square(x)
    x ** 2
  end
end

But the following does NOT work:

module Math
  def square(x)
    x ** 2
  end
end

Why is this? For reference, the method is being called like puts Math.square(6)

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Ricky
  • 2,850
  • 5
  • 28
  • 41

2 Answers2

8

Within the context of a module, declaring a method with self as a prefix makes it a module method, one that can be called without having to include or extend with the module.

If you'd like to have mix-in methods, which is the default, and module methods, which requires the self prefix, you can do this:

module Math
  # Define a mix-in method
  def square(x)
    x ** 2
  end

  # Make all mix-in methods available directly
  extend self
end

That should have the effect of making these methods usable by calling Math.square directly.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • Thanks! So if I understand correctly, declaring without "self" would force me to use a mixin like include or extend wherever I want to use it... Whereas declaring with "self" will allow me to call it like MyModule.MyMethod ? – Ricky Apr 25 '13 at 14:34
  • Exactly. A similar sort of thing plays out with classes, only instead of `include` and `extend`, you inherit. – tadman Apr 25 '13 at 14:52
0

In method definition, if you do not have self., then it is defined on an instance of that class. Since Math is not an instance of Math, it will not work without it.

sawa
  • 165,429
  • 45
  • 277
  • 381