From: Rick DeNatale Date: 2009-02-05T06:04:36+09:00 Subject: Re: Making object methods available externally --001636163cc7370bd304621e24e9 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit On Wed, Feb 4, 2009 at 3:06 PM, Rob Biedenharn wrote: > > When you need it, yes. However, it isn't typical that you'd do something > like this. Either the method belongs on the instance or it belongs on the > class itself. Occasionally, for convenience, you want a class method to be > called on an instance and then you'd likely do it this way. Your example is > simple (and, being an example, somewhat contrived), but illustrates a point. > You can call #say_it with no parameter because the instance variable is > there so an instance *knows* what to say, but to call .say_it on the class, > you need to pass the parameter. > Ruby does have a method Module#module_function which can be used in cases similar to this. For a rather silly example: module Test def foo puts "Foo" end module_function :foo end Test.foo begin foo rescue Exception => ex puts "oops! #{ex}" end self.extend Test foo when run produces: Foo oops! undefined local variable or method `foo' for main:Object Foo What module_function does is to copy one or more instance methods and make them singleton methods of the module. It only works for modules not classes. The canonical use case is in the Math module so that you can either write: Math.sin(.2) or class X include Math def compute(val) 2 + sin(val) end end -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Twitter: http://twitter.com/RickDeNatale --001636163cc7370bd304621e24e9--