簡體   English   中英

Ruby-遍歷並調用方法數組

[英]Ruby - Iterating over and calling an array of methods

可以說我有兩種方法:

def hello
 'hello'
end

def world
 'world'
end

現在,我要以這種方式調用這些方法:

try_retry{
  hello
}
try_retry{
  world
}

假設try_retry是一種方法,如果發生錯誤,該方法將重試代碼塊。 這些方法很多,是否有可能遍歷塊? 就像是:

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

問題是方法在這一行得到評估:

array_of_methods = [hello,world]

你可以做

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

你可以像這樣稱呼他們

array_of_methods.each { |m| m.call }

假設您擁有helloworld方法。 如果要在遍歷它們的同時調用這些方法,則可以這樣做

['hello', 'world'].each do |m|
  send(m)
end

根據此方法名稱數組的來源,您可能不希望允許調用私有方法或受保護的方法,因此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