3
>> [1, 2, 3, 4, 5].any? {|n| n % 3 == 0}
=> true

如果我想知道哪个项目匹配,而不仅仅是一个项目是否匹配?我只对短路解决方案感兴趣(一旦找到匹配项就停止迭代的解决方案)。

我知道我可以执行以下操作,但由于我是 Ruby 新手,我很想学习其他选项。

>> match = nil
=> nil
>> [1, 2, 3, 4, 5].each do |n|
..   if n % 3 == 0
..     match = n
..     break
..   end
.. end
=> nil
>> match
=> 3
4

3 回答 3

6

您是否正在寻找这个:

[1, 2, 3, 4, 5].find {|n| n % 3 == 0} # => 3

文档

将枚举中的每个条目传递给阻塞。返回第一个不为假的块。

因此,这也将满足您的“短路”要求。另一个可能不太常用的别名Enumerable#findis Enumerable#detect,它的工作方式完全相同。

于 2011-10-12T04:56:43.757 回答
5

如果您想要您的块为真的第一个元素,请使用detect

[1, 2, 3, 4, 5].detect {|n| n % 3 == 0}
# => 3

如果您想要匹配的第一个元素的索引find_index,请使用:

[1, 2, 3, 4, 5].find_index {|n| n % 3 == 0}
# => 2

如果您想要所有匹配的元素,请使用select(这不会短路):

[1, 2, 3, 4, 5, 6].select {|n| n % 3 == 0}
# => [3, 6]
于 2011-10-12T04:59:48.650 回答
3

如果你想要短路行为,你想要 Enumerable#find,而不是选择

ruby-1.9.2-p136 :004 > [1, 2, 3, 4, 5, 6].find  {|n| n % 3 == 0}
 => 3 
ruby-1.9.2-p136 :005 > [1, 2, 3, 4, 5, 6].select  {|n| n % 3 == 0}
 => [3, 6] 
于 2011-10-12T04:57:21.463 回答