Forum: Ruby class << Foo; include Foo; end

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
8029153bbcbda4a6844440c93e0c6422?d=identicon&s=25 Thomas Hafner (Guest)
on 2007-04-09 01:10
(Received via mailing list)
Hello,

how should I group some stateless functions into a module and use them
in a very simple way without littering the namespace? E.g. if the
module is ``Foo'' with at least one function foo, then I'd like to use
that module in a way as simple like that:

  require 'Foo'
  puts Foo.foo("world")

The first solution that I've found is to write Foo.rb like follows:

  module Foo
    def foo(s)
      "Hello, #{s}\n"
    end
  end

  class << Foo
    include Foo
  end

Is that Ok? Or is there even a simpler way?

Regards
  Thomas
E7559e558ececa67c40f452483b9ac8c?d=identicon&s=25 Gary Wright (Guest)
on 2007-04-09 01:30
(Received via mailing list)
On Apr 8, 2007, at 7:10 PM, Thomas Hafner wrote:
>   end
That is fine.  There are several variations:

module Foo
   def foo(s)
     "Hello, #{s}\n"
   end
   extend self
end

Your example and my variation enable the module to
respond to *all* of its instance methods.

If you only want the module to respond to some of its instance
methods you'll want to look at the following variations:

module Foo
   def foo(s)
     "Hello, #{s}\n"
   end
   module_function :foo
end

or

module Foo;end
def Foo.foo(s)
   "Hello, #{s}\n"
end




Gary Wright
852a62a28f1de229dc861ce903b07a60?d=identicon&s=25 Gavin Kistner (phrogz)
on 2007-04-09 06:25
(Received via mailing list)
On Apr 8, 5:05 pm, Thomas Hafner <tho...@hafner.NL.EU.ORG> wrote:
> how should I group some stateless functions into a module and use them
> in a very simple way without littering the namespace? E.g. if the
> module is ``Foo'' with at least one function foo, then I'd like to use
> that module in a way as simple like that:
>
>   require 'Foo'
>   puts Foo.foo("world")

module Foo
  def self.foo( msg )
    puts "Hello #{msg}"
  end
end
This topic is locked and can not be replied to.