[英]How can I refactor ruby code that calls different functions but does the same thing with their responses?
這是我重構的方法。 重構此代碼的好方法是什么? 有沒有辦法將方法調用放在列表中,並在方法之一返回有效響應時返回?
def method
response_hash = method1
return response_hash if response_hash.present?
response_hash = method2
return response_hash if response_hash.present?
response_hash = method3
return response_hash if response_hash.present?
response_hash = method4
return response_hash if response_hash.present?
end
似乎您想要返回第一個非空結果。
def my_method
[:method1, :method2, :method3, :method4].each do |method_name|
result = send(method_name)
return result if result.present?
end
end
符號/ send
在這里是為了保持評估的惰性(不要評估超過必要的)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.