【问题标题】:What's the fastest way in Ruby to get the first enumerable element for which a block returns true?Ruby 中获取第一个块返回 true 的可枚举元素的最快方法是什么?
【发布时间】:2012-04-03 23:06:42
【问题描述】:

在 Ruby 中获取第一个块返回 true 的可枚举元素的最快方法是什么?

例如:

arr = [12, 88, 107, 500]
arr.select {|num| num > 100 }.first  # => 107

我不想像select 那样遍历整个数组,因为我只需要第一个匹配项。

我知道我可以做一个each 并在成功时中断,但我认为有一种本地方法可以做到这一点;我只是没有在文档中找到它。

【问题讨论】:

    标签: ruby arrays enumerable


    【解决方案1】:
    arr.find{|el| el>100} #107 (or detect; it's in the Enumerable module.)
    

    【讨论】:

      【解决方案2】:

      几个核心 ruby​​ 类,包括 ArrayHash 包括 Enumerable 模块,它提供了许多有用的方法来处理这些枚举。

      这个模块提供了find or detect methods,它完全符合您的要求:

      arr = [12, 88, 107, 500]
      arr.find { |num| num > 100 } # => 107
      

      两个方法名是同义词,作用完全相同。

      【讨论】:

      • 啊! find 是我试图记住的方法。愚蠢的我,我正在查看 Array 的文档,而不是 Enumerable
      • 在 Ruby 世界中也称为 detect
      • 同义词一致。我个人更喜欢find(当我不在Rails 环境中时更是如此)。但你是对的,一般使用detect 可能会更好。
      • 更新 - 我现在总是使用 detect 别名。我很容易记住 select reject detect 并且不会与 ActiveRecord 的 find 混淆。
      【解决方案3】:

      我记得 ActiveRecord.find 的用法,它为您获取第一条记录和 ActiveRecord.select,您在获取所有记录时使用它。

      不是一个完美的比较,但可能足以帮助记住。

      【讨论】:

        猜你喜欢
        • 2012-10-17
        • 1970-01-01
        • 1970-01-01
        • 2016-01-23
        • 1970-01-01
        • 2017-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多