0

Lets say I have two methods:

def hello
 'hello'
end

def world
 'world'
end

Now I want to call these methods in a fashion like this:

try_retry{
  hello
}
try_retry{
  world
}

assume try_retry is a method that will retry the block of code if an error happens. There are a lot of these methods so is it possible to iterate over the blocks? Something like:

array_of_methods = [hello,world]
array_of_methods.each do |method|
  try_retry{
    method
  }
end

the problem is the methods get evaluated on this line:

array_of_methods = [hello,world]
C dot StrifeVII
  • 1,885
  • 1
  • 16
  • 21

3 Answers3

1

You can do

array_of_methods = [method(:hello), method(:world)]

And you can call them like

array_of_methods.each { |m| m.call }
Ursus
  • 29,643
  • 3
  • 33
  • 50
  • Note: with this answer `method(:hello)` is an object for the method `hello` and does not directly call the method. This is very nice because you have more options as to what to do with the method, but if you are only calling the method, using `send` is more efficient. – Eli Sadoff Oct 20 '16 at 18:45
0

Let's say that you have the methods hello and world. If you want to call these methods while iterating over them, you can do it as such

['hello', 'world'].each do |m|
  send(m)
end
Eli Sadoff
  • 7,173
  • 6
  • 33
  • 61
  • 1
    Method names are usually symbols. Besides, you have to call `send` within `try_retry { ... }` to actually solve the OPs problem. – Stefan Oct 20 '16 at 19:12
0

Depending on the origin of this array of method names you might not want to allow private or protected methods to get called so public_send will allow for only public methods to be called.

array_of_methods = ['hello', 'world']

array_of_methods.each {|m| public_send(m)}
C dot StrifeVII
  • 1,885
  • 1
  • 16
  • 21