It's pretty easy to return a method like a proc from a module:
module Foo
def self.bar
# Method implementation
end
def self.baz
# Method implementation
end
def self.qux
# Method implemenatation
end
def self.zoo
# Method implementation
end
end
Foo.method(:bar) # Returns a proc object
But what if I want to return more than one (but not all of them) method from the same module?
One way to do that is:[:bar,:baz].inject([]) {|memo,i| memo << Foo.method(i)}
Is there a better, more agile way to do the same?
You can always use monkey patching to make it look however you wish:
class Object
def get_methods(*methods)
methods.map { |m| method(m) }
end
end
module Foo
def self.bar
# Method implementation
end
def self.baz
# Method implementation
end
end
Foo.get_methods(:foo, :baz)
Try this:
Foo.methods(false).map {|e| Foo.method(e)}
Foo.methods(false)
will return all class methods that are not inherited as an array and map
will iterate over each element.
EDIT
After taking into account the comments below:
proc_arr = [:bar, :baz].map {|e| Foo.method(e)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With