红宝石 |可枚举的detect()函数
enumerable的detect()是 Ruby 中的一个内置方法,它返回满足块中给定条件的第一个元素。如果没有块,则返回枚举器本身。
Syntax: block.detect { |obj| block }
Parameters: The function takes the block according to which the first which satisfies is to be returned.
Return Value: It returns the first element which satisfies the block or the enumerator instead.
示例 1 :
# Ruby program for detect method in Enumerable
# Initialize
enu = (1..50)
# returns first element
enu.detect { |el| el % 2 == 0 && el % 9 == 0}
输出:
18
示例 2 :
# Ruby program for detect method in Enumerable
# Initialize
enu = (1..50)
# returns enumerator
enu.detect
输出:
Enumerator: 1..50:detect