Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to eval / constantize a string to a method, then pass arguments to it

Given:

s = "foo_bar_path"

How can I eval or constantize s, and pass arguments to it, such as my final result would be the equivalent of:

foo_bar_path(@myvar, @foobar)

I was trying eval(s).send but that doesn't seem to work. And constantize seems to only work on Classes?

like image 418
Geremy Avatar asked Dec 28 '25 06:12

Geremy


2 Answers

You would just use the send method (or public_send depending on your needs) on the appropriate object:

some_object.send(s, @myvar, @foobar)

or if you want to call a method on yourself:

self.send(s, @myvar, @foobar)

The documentation says "symbol" but send is just as happy to get the method name in a string.

like image 74
mu is too short Avatar answered Dec 30 '25 19:12

mu is too short


Another way to go about this sort of this sort of thing (better for OpenStruct):

#for more in this domain, see the Ruby core API for the Object class
class Demo
  def initialize(n)
    @iv = n
  end
  def hello()
    "Hello, @iv = #{@iv}"
  end
end

k = Demo.new(99)
m = k.method(:hello)
m.call   #=> "Hello, @iv = 99"
like image 30
boulder_ruby Avatar answered Dec 30 '25 19:12

boulder_ruby



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!