Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: better way to return several methods as procs from a module

Tags:

ruby

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?

like image 326
DreamWalker Avatar asked Dec 13 '15 12:12

DreamWalker


2 Answers

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)
like image 86
Amr Noman Avatar answered Sep 30 '22 10:09

Amr Noman


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)}
like image 20
Brozorec Avatar answered Sep 30 '22 10:09

Brozorec