红宝石 |可枚举的 find()函数
enumerable的find()是 Ruby 中的一个内置方法,它返回满足块中给定条件的第一个元素。如果没有块,则返回枚举器本身。
Syntax: block.find { |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 find method in Enumerable
# Initialize
enu = (1..50)
# returns first element
enu.find { |el| el % 2 == 0 && el % 9 == 0}
输出:
18
示例 2 :
# Ruby program for find method in Enumerable
# Initialize
enu = (1..50)
# returns enumerator
enu.find
输出:
Enumerator: 1..50:find