From: James Hunt Date: 2007-09-09T16:37:25+09:00 Subject: Re: module_function :func vs. MyModule.func? On 9/9/07, 7stud -- wrote: > 7stud -- wrote: > > > > module MyModule > > def greet > > puts "hello" > > end > > end > > > > module OtherModule > > include MyModule > > > > module_function :greet > > end > > > > OtherModule.greet > > > On p. 355 of "Programming Ruby (2nd ed)", there is the equivalent of > this example: > > module MyModule > def greet > puts "hello" > end > > module_function :greet > end > > MyModule.greet > > As far as I can tell, in that example the module_function has no purpose > since I could just as easily make this change: > > module MyModule > def MyModule.greet > puts "hello" > end > end > > MyModule.greet > > Is there any reason to use module_function in that example? > > > -- > 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 # (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 -- James