From: Robert Klemme Date: 2011-11-25T06:51:13+09:00 Subject: Re: How to Design Module Method? On Thu, Nov 24, 2011 at 7:13 PM, Admin Tensor wrote: > Hi, > > If I define a module method like this: > >  module MyMod >    def MyMod.my_method >    end >  end > > then I can invoke it like this: > >  irb> MyMod.my_method >  => nil > > but I cannot invoke my_method without the module name, even if I include > the module: > >  irb> include MyMod >  => Object >  irb> my_method >  NameError: undefined local variable or method `my_method' for > main:Object > > Now, if I define the method like this: > >  module MyMod >    def my_method >    end >  end > > then I cannot invoke my_method even with the module name: > >  irb> MyMod.my_method >  NoMethodError: undefined method `my_method' for MyMod:Module > > but I can invoke it if I include the module: > >  irb> include MyMod >  => Object >  irb> my_method >  => nil > > Therefore, my question is, is there any way so that both means of > invoking work, i.e., for people who don't "include" the module they can > type "MyMod.my_method", and for people who "include" the module they can > simply type "my_method"?  (I am using Ruby 1.9.2.) There are various methods, this is one of them: irb(main):001:0> module Foo irb(main):002:1> def bar;123;end irb(main):003:1> extend self irb(main):004:1> end => Foo irb(main):005:0> Foo.bar => 123 irb(main):006:0> class X irb(main):007:1> include Foo irb(main):008:1> def test;bar;end irb(main):009:1> end => nil irb(main):010:0> X.new.test => 123 BUT: both uses are quite different. When invoking on the module you are basically using an algorithm which typically does not use context (read: "state"). When invoking on the instance of a class which includes the module then it can potentially use context (i.e. instance state). Both uses are quite different which is why I generally suggest to not do this and keep aspects separate and not do this "dual use". Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/