简体   繁体   中英

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]

You can do

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

And you can call them like

array_of_methods.each { |m| m.call }

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

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)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM