Checking if any element of an array satisfies a condition

Possible Duplicate:
check if value exists in array in Ruby

I have this method which loops through an array of strings and returns true if any string contains the string 'dog'. It is working, but the multiple return statements look messy. Is there a more eloquent way of doing this?

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

Use Enumerable#any?

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

It will return true / false .

链接地址: http://www.djcxy.com/p/25670.html

上一篇: 检查数组数组是否包含某个数组

下一篇: 检查数组的任何元素是否满足条件