Matchu
Matchu

Reputation: 85794

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_foo to make the last line work as expected? (send_to_foo is obviously not how I would implement this; it just makes clearer what I'm looking for.)

I expected Foo.send(:bar) to work at first, but it makes sense that it doesn't. It would if the method were defined as def self.bar, but that's no fun.

Upvotes: 3

Views: 1132

Answers (1)

rampion
rampion

Reputation: 89043

well, the 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

Upvotes: 2

Related Questions