37

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
Community
  • 1
  • 1
k_Dank
  • 685
  • 1
  • 7
  • 17
  • 3
    I think that other question only checks to see if one of the array elements `== "dog"` which is distinct from any of the array elements containing that string. – k_Dank Oct 11 '12 at 18:34

1 Answers1

63

Use Enumerable#any?

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

It will return true/false.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367