【问题标题】:Checking if any element of an array satisfies a condition [duplicate]检查数组的任何元素是否满足条件[重复]
【发布时间】:2012-10-01 09:43:12
【问题描述】:

可能重复:
check if value exists in array in 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

【问题讨论】:

  • 我认为其他问题只检查数组元素之一 == "dog" 是否与包含该字符串的任何数组元素不同。

标签: ruby


【解决方案1】:

使用Enumerable#any?

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

它将返回true/false

【讨论】:

  • 啊,是的,语义上比detect好。
猜你喜欢
  • 2017-06-20
  • 2013-03-06
  • 1970-01-01
  • 1970-01-01
  • 2016-04-26
  • 1970-01-01
  • 1970-01-01
  • 2017-08-09
  • 2021-12-07
相关资源
最近更新 更多