Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why prefix a method with "self"

Tags:

ruby

self

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)

like image 913
Ricky Avatar asked Oct 24 '25 02:10

Ricky


1 Answers

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.

like image 171
tadman Avatar answered Oct 25 '25 17:10

tadman



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!