On 9/9/07, 7stud – [email protected] wrote:
def greet
–
Posted via http://www.ruby-forum.com/.
I believe the primary different shows up when the module is included
in another class. Consider this little snippet:
module MyModule
def greet
puts “hello”
end
module_function :greet
end
class MyClass
include MyModule
def hello
greet
end
end
MyModule.greet
MyClass.new.hello
When this gets run, the output will be:
hello
hello
The kicker is that greet is mixed into MyClass as a private method
(try calling MyClass.new.greet and watch the access error).
Using your explicit definition as such:
module MyExplicitModule
def MyExplicitModule.greet
puts “hello, explicitly!”
end
end
class MyExplicitClass
include MyExplicitModule
def hello
greet
end
end
MyExplicitModule.greet
MyExplicitClass.new.greet
The output of this code when run is
hello
module_function.rb:31:in hello': undefined local variable or method
greet’ for #MyExplicitClass:0xb7cc7eac (NameError)
from module_function.rb:36
Essentially, by defining explicitly as MyExplicitModule.greet, the
method becomes a member of the module’s singleton class, and does not
get mixed into classes that include it. The module_function call
makes the method passed private and creates a singleton method.
You may also want to check out:
http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/17670
The poster gives a good example of the usage (Math.sqrt)
HTH