简体   繁体   English

Ruby-遍历并调用方法数组

[英]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. 假设try_retry是一种方法,如果发生错误,该方法将重试代码块。 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 . 假设您拥有helloworld方法。 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. 根据此方法名称数组的来源,您可能不希望允许调用私有方法或受保护的方法,因此public_send仅允许调用公共方法。

array_of_methods = ['hello', 'world']

array_of_methods.each {|m| public_send(m)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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