Is there a method.send equivalent for proc? eg:
def s a
a + 1
end
b = "s"
send b.to_sym,10 #=> 11
Is there something like this?
p = Proc.new{|s| s + 1}
d = "p"
*call d.to_sym,10 *
EDIT: In response to mudasobwa's answer I need to call the Procs from an array of methods. eg:
ss = ["a","b","c","d"]
Is it possible in this case?
Fortunately, Ruby's metaprogramming feature allows us to call methods dynamically by just passing the method name into public_send(method_name) or send(method_name) . We can call the make_noise method by calling Duck. new. public_send("make_noise") , this is equivalent to calling Duck.
The purpose of the . call method is to invoke/execute a Proc/Method instance.
A Proc object is an encapsulation of a block of code, which can be stored in a local variable, passed to a method or another Proc, and can be called. Proc is an essential concept in Ruby and a core of its functional programming features.
The other answers cover the exact question asked. But I say, it was a wrong approach. Don't do that runtime introspection. It brings no benefit. If you want to address your procs by name, put them in a hash and use "civilian-grade" ruby.
handlers = {
'process_payment' => proc { ... },
'do_this' => proc { ... },
'or_maybe_that' => proc { ... },
}
pipeline = ['process_payment', 'or_maybe_that']
pipeline.each do |method_name|
handlers[method_name].call
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With