问题
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)
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/16217401/why-prefix-a-method-with-self