33

可能重复:
检查值是否存在于 Ruby 中的数组中

我有这个方法,它遍历一个字符串数组,如果任何字符串包含字符串'dog',则返回true。它正在工作,但多个返回语句看起来很乱。有没有更雄辩的方式来做到这一点?

def has_dog?(acct)
  [acct.title, acct.description, acct.tag].each do |text|
    return true if text.include?("dog")
  end
  return false
end
4

1 回答 1

59

使用Enumerable#any?

def has_dog?(acct)
  [acct.title, acct.description, acct.tag].any? { |text| text.include? "dog" }
end

它将返回true/ false

于 2012-10-10T20:10:21.673 回答