ruby - Why prefix a method with "self" -


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

one of exercises asks me to

...define static method square in module math. should return square of number passed it...

why work when prefix method definition "self"? e.g. following works:

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

but following not work:

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

why this? reference, method being called puts math.square(6)

within context of module, declaring method self prefix makes module method, 1 can called without having include or extend module.

if you'd have mix-in methods, default, , module methods, requires self prefix, can this:

module math   # define mix-in method   def square(x)     x ** 2   end    # make mix-in methods available directly   extend self end 

that should have effect of making these methods usable calling math.square directly.


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -