Ruby检测方法 [英] Ruby Detect method

查看:57
本文介绍了Ruby检测方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

选择很有意义.但是有人可以向我解释.我不明白这些数据.

Select makes sense. But can someone explain .detect to me? I don't understand these data.

>> [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]

推荐答案

Detect返回列表中该块返回TRUE的第一项.您的第一个示例:

Detect returns the first item in the list for which the block returns TRUE. Your first example:

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

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

Returns 3 because that is the first item in the list that returns TRUE for the expression x.between?(3,4).

detect 停止迭代. select 将迭代直到到达输入列表的末尾,并返回该块返回true的所有项目.

detect stops iterating after the condition returns true for the first time. select will iterate until the end of the input list is reached and returns all of the items where the block returned true.

这篇关于Ruby检测方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆