Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send instance method to module

Tags:

module

ruby

send

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.

like image 618
Matchu Avatar asked May 11 '26 13:05

Matchu


1 Answers

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
like image 200
rampion Avatar answered May 14 '26 05:05

rampion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!