【问题标题】:Ruby Detect method红宝石检测方法
【发布时间】:2011-02-28 12:49:13
【问题描述】:

选择是有意义的。但是有人可以向我解释 .detect 吗?我不明白这些数据。

>> [1,2,3,4,5,6,7].detect { |x| x.between?(3,4) }
=> 3
>> [1,2,3,4,5,6,7].detect { |x| x.between?(3,6) }
=> 3
>> [1,2,3,4,5,6,7].detect { |x| x.between?(3,7) }
=> 3
>> [1,2,3,4,5,6,7].detect { |x| x.between?(2,7) }
=> 2
>> [1,2,3,4,5,6,7].detect { |x| x.between?(1,7) }
=> 1
>> [1,2,3,4,5,6,7].detect { |x| x.between?(6,7) }
=> 6
>> [1,2,3,4,5,6,7].select { |x| x.between?(6,7) }
=> [6, 7]
>> [1,2,3,4,5,6,7].select { |x| x.between?(1,7) }
=> [1, 2, 3, 4, 5, 6, 7]

【问题讨论】:

    标签: ruby detect


    【解决方案1】:

    检测返回列表中块返回 TRUE 的第一个项目。你的第一个例子:

    >> [1,2,3,4,5,6,7].detect { |x| x.between?(3,4) }
    => 3
    

    返回3,因为这是列表中为表达式x.between?(3,4) 返回TRUE 的第一项。

    detect 在条件第一次返回 true 后停止迭代。 select 将迭代直到到达输入列表的末尾,并返回块返回 true 的所有项目。

    【讨论】:

    • “检测”的别名是“查找”。对我来说,如果我将其视为“查找”,则更容易理解该方法的语义。
    • 然而,交替使用“检测”和“查找”似乎并不正确。如果您检查 ruby​​ 文档,如果事实上它在检测和查找示例代码中都指出它们的行为不同。实际上很难弄清楚“find”和“detect”之间的区别,因为两种方法的解释性文本~完全相同~相同,但解释方法不同。 ruby-doc.org/core-2.2.1/Enumerable.html#method-i-find
    • @PaulDacus 但是,当您扩展源代码时,#detect 指向 enum_find(...)。所以我假设#detect 是#find here 的别名。
    • @PaulDacus RubyDocs 中 detectfind 的解释方法表现不同,因为它们被不同的对象调用:(1..10) vs (1..100)
    【解决方案2】:

    detect 只返回满足谓词的第一个值,如果有,则返回 nil。 select 返回所有满足谓词的值。 a.detect { p } 类似于 a.select { p }[0]

     irb(main):001:0> [1,2,3].detect { true }
     => 1
     irb(main):002:0> [1,2,3].detect { false }
     => nil
     irb(main):003:0> [1,2,3].detect { |x| x % 2 == 0 }
     => 2
    

    【讨论】:

      【解决方案3】:

      当您想了解这些方法时,ruby-docs 是一个很好的资源。

      Enumerable#detect

      【讨论】:

        【解决方案4】:

        finddetect 将始终返回单个对象,或者如果没有匹配项,它们将返回 nil

        [1,2,3,4,5,6,7].detect { |x| x.between?(1,7) }
        => 1
        

        find_allselect 将返回它找到匹配的数组:

        [1,2,3,4,5,6,7].select { |x| x.between?(1,7) }
        => [1, 2, 3, 4, 5, 6, 7]
        

        Reference Link

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-03-21
          • 1970-01-01
          • 1970-01-01
          • 2013-03-19
          • 2010-09-08
          • 2023-04-07
          • 2019-06-18
          • 1970-01-01
          相关资源
          最近更新 更多