Send instance method to module

Given the following module,

module Foo
  def bar
    :baz
  end
end

def send_to_foo(method)
  # ...?
end

send_to_foo(:bar) # => :baz

What code should go in send_to_foofor the last job to work as expected? ( send_to_fooobviously not the way I would have done it, it just clarifies what I'm looking for.)

I expected it Foo.send(:bar)to work first, but it makes sense that it is not. If the method were defined as def self.bar, but it is not funny.

+3
source share
1 answer

well, an easy way would be

Foo.extend Foo # let Foo use the methods it contains as instance methods
def send_to_foo(method)
  Foo.send(method)
end

So now

irb> send_to_foo(:bar)
 #=> :baz
+2
source

Source: https://habr.com/ru/post/1741623/


All Articles