我必须编写一个 Ruby 方法:
遍历数组,如果其中一个元素符合特定条件则执行 Foo。
如果没有数组元素符合条件,则执行 Bar 操作。
在任何其他语言中,我会在进入循环之前设置一个 bool 变量,并在执行 Foo 时切换它。该变量的值会告诉我是否需要 Bar。但这感觉不像 Rubyish 那样不优雅。谁能提出更好的方法?
编辑 一些非常好的答案,但由于我本应提及的细节,它们不太有效。 Foo 所做的事情是对符合条件的数组元素完成的。此外,保证最多有一个元素匹配条件。
最佳答案
是否有任何项目匹配?如果是,则做一些不涉及匹配项目的事情。
if items.any? { |item| item.totally_awesome? }
foo "we're totally awesome!"
else
bar "not awesome :("
end
抓取第一个匹配项。如果它存在,则使用匹配项做一些事情。
awesome_item = items.find { |item| item.totally_awesome? }
if awesome_item
foo "#{awesome_item.name} is totally awesome!"
else
bar "no items are awesome :("
end
抓取所有匹配项。如果数组中有任何内容,则对所有匹配项执行操作。
awesome_items = items.find_all { |item| item.totally_awesome? }
if awesome_items.any?
foo "#{awesome_items.size} totally awesome items!"
else
bar "no items are awesome :("
end
关于ruby - Ruby 中优雅的循环 Elsing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14514233/