Ruby - Iterating over and calling an array of methods

时间:2016-10-20 18:40:29

标签: arrays ruby loops ruby-block

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]

3 个答案:

答案 0 :(得分:1)

You can do

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

And you can call them like

array_of_methods.each { |m| m.call }

答案 1 :(得分: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

答案 2 :(得分: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)}