Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i dynamically call a Proc in Ruby?

Tags:

ruby

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?

like image 295
B A Avatar asked Nov 29 '16 12:11

B A


People also ask

How do you call a method dynamically in Ruby?

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.

What does .call do in Ruby?

The purpose of the . call method is to invoke/execute a Proc/Method instance.

How does Proc work in Ruby?

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.


1 Answers

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
like image 91
Sergio Tulentsev Avatar answered Oct 18 '22 02:10

Sergio Tulentsev