class << Foo; include Foo; end

T

Thomas Hafner

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
 
G

Gary Wright

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

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
 
P

Phrogz

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,228
Latest member
MikeMichal

Latest Threads

Top