Ruby: the best way to return multiple methods as procs from a module

It is very easy to return a method, for example, 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 method (but not all) from the same module? One way to do this is: [:bar,:baz].inject([]) {|memo,i| memo << Foo.method(i)} [:bar,:baz].inject([]) {|memo,i| memo << Foo.method(i)}

Is there a better, more flexible way to do the same?

+6
source share
3 answers

You can always use the monkey patch to make it look as you like:

 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) 
+2
source

Try the following:

 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 considering the comments below:

 proc_arr = [:bar, :baz].map {|e| Foo.method(e)} 
+2
source

I don't know if there is a better way, but maybe this is a little cleaner than your solution:

 proc_methods = [] # => [] (Foo.methods - Object.methods).each { |m| proc_methods << Foo.method(m) } # => [:bar, :baz] proc_methods # => [#<Method: Foo.bar>, #<Method: Foo.baz>] 

Foo inherits its methods from the Object class, which is the default root of all Ruby objects. ( http://ruby-doc.org/core-2.2.3/Object.html )

With Foo.methods - Object.methods you only save your own methods.

+1
source

All Articles