Hi,
I need to create a set of functions and I’m wondering what’s the best
way to achieve it.
- A singleton class that holds all the functions
- A class with only class methods ( def self.method_name …)
- A Module ? (I don’t really know what are the advantages of module in
that case)
The functions don’t need instance attributes so I guess singleton class
is not really needed here.
What’s your opinion on this ?
Thanks a lot for your help.
PS: Sorry for my poor english
H.
hi Harold,
from what i understand, a module is most likely what you’re looking
for here… someone else could probably explain what goes on under the
hood much better than i can (and hopefully they will!) but a module is
usually used in cases where you just want to hold a collection of
constants and methods which can later be used in any class you include
the module in. here’s a simple example:
module Funcs
def caps(array)
array.each{|i| puts i.capitalize}
end
def backwards(array)
newarray = []
array.each{|i| newarray.insert(0, i)}
puts newarray
end
end
class Example
include Funcs
def initialize
a = %W[funky chunky monkey]
caps(a)
backwards(a)
end
end
e = Example.new
take a look here for more info - The Ruby Language FAQ: Classes and modules
cheers,
p.s. i’d say your english is quite good!
jake kaiden wrote in post #1007290:
def backwards(array)
newarray = []
array.each{|i| newarray.insert(0, i)}
puts newarray
end
end
haha - guess i’m reinventing the wheel here a bit, “array.reverse!”
would work just as well!
Harold W. wrote in post #1007266:
I need to create a set of functions and I’m wondering what’s the best
way to achieve it.
- A singleton class that holds all the functions
- A class with only class methods ( def self.method_name …)
- A Module ? (I don’t really know what are the advantages of module in
that case)
I’d say a Module. If these functions are standalone (not to be mixed
into a class) then you can define them like this:
module Foo
def self.bar
puts “yo”
end
end
Foo.bar
But there’s another option:
module Foo
def bar
puts “yo”
end
module_function :bar
end
I believe in this case you can call it as Foo.bar, and mix the module
into a class.