I want to put a method in a Ruby module such that it can be called from a class method or an instance method, using simple syntax:
module MyMod
def fmt *args
args.map { | a | "You said #{a}" }
end
end
class MyClass
include MyMod
def inst
puts fmt 1,2,3
end
def self.cls
puts fmt 4,5,6
end
end
The above doesn’t work because the class method (cls) can’t see the instance method fmt. If I change the definition to self.fmt, then the instance method has to invoke it as MyMod.fmt.
I’d like to be able to just invoke fmt (some stuff) from both types of method. Is there a “ruby-ish” way of doing this? I can define the module as
module MyMod
def self.fmt *args
args.map { | a | "You said #{a}" }
end
def fmt *args
MyMod.fmt args
end
end
but that’s not very DRY, is it? Is there a simpler way?
You can use advantage of
Module#includedmethod to do it like that:And here’s the output:
For more detailed explanation have a look at this article.