Ruby 具有条件的数组的第一个元素
找到数组中满足某些条件的第一个元素的方法是否比以下方法更短:Ruby 具有条件的数组的第一个元素,ruby,arrays,Ruby,Arrays,找到数组中满足某些条件的第一个元素的方法是否比以下方法更短: my_array[ my_array.index {|x| x.some_test} ] 试试这个: my_array.find{|x| x.some_test } 或者这里有一条捷径(谢谢@LarsHaugseth提醒) 至于我,我觉得听起来很困惑。因为我期望收到多个这样的请求对象 我更喜欢使用detect来获取不同的代码 然后选择,以查找所有代码 下面是ruby文档介绍的内容: detect(ifnone = nil) {|
my_array[ my_array.index {|x| x.some_test} ]
试试这个:
my_array.find{|x| x.some_test }
或者这里有一条捷径(谢谢@LarsHaugseth提醒)
至于我,我觉得听起来很困惑。因为我期望收到多个这样的请求对象 我更喜欢使用
detect
来获取不同的代码
然后选择,以查找所有代码
下面是ruby文档介绍的内容:
detect(ifnone = nil) {| obj | block } → obj or nil click to toggle source
find(ifnone = nil) {| obj | block } → obj or nil
detect(ifnone = nil) → an_enumerator
find(ifnone = nil) → an_enumerator
将枚举中的每个项传递给块。返回块不为false的第一个块。如果没有匹配的对象,则调用ifnone并在指定时返回其结果,否则返回nil
find_all {| obj | block } → array click to toggle source
select {| obj | block } → array
find_all → an_enumerator
select → an_enumerator
返回一个数组,该数组包含enum的所有元素,其中block不是false可以缩短为
my_数组。find(&:some_test)
find/detect、map/collect、reduce/inject-每个人都有一个方法:)对我来说,detect
听起来根本不是一个正确的方法find
至少可以找到并返回一些东西。detect
做了什么和返回了什么?如果不查阅文档,我就不知道了。不过,ruby社区基本上还是选择了find
。切换的一个很好的理由。detect
在处理活动记录对象等时很有用(其中find
被覆盖并执行DB查询)
find_all {| obj | block } → array click to toggle source
select {| obj | block } → array
find_all → an_enumerator
select → an_enumerator