arraysrubyloopsruby-block

Ruby - Iterating over and calling an array of methods


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]

Solution

  • You can do

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

    And you can call them like

    array_of_methods.each { |m| m.call }