2012-10-10 140 views
26

可能重複:
check if value exists in array in Ruby檢查如果一個數組中的任何元素滿足條件

我已經這種方法,其循環通過一個字符串數組,並返回true,如果任何字符串包含字符串'狗'。它正在工作,但多個返回語句看起來很混亂。有沒有更加雄辯的方式來做到這一點?

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

我認爲其他問題只檢查是否有一個數組元素「==」dog「'與任何包含該字符串的數組元素不同。 –

回答

46

使用Enumerable#any?

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

它將返回true/false

+1

啊,是的,在語義上比'detect'更好。 – meagar

相關問題