红宝石 |可枚举的 select()函数
enumerable的select()是 Ruby 中的一个内置方法,它返回 enumerable 中满足块中给定条件的项目。如果没有给出块,它返回一个枚举器。
Syntax: enu.select { |obj| block }
Parameters: The function takes a block whose condition is used to find the elements.
Return Value: It returns the items in the enum which satisfies the condition in the block. Iy t returns an enumerator if no block is given.
示例 1 :
# Ruby program for select method in Enumerable
# Initialize
enu = (1..10)
# Prints
enu.select { |obj| obj % 2 == 1}
输出:
[1, 3, 5, 7, 9]
示例 2 :
# Ruby program for select method in Enumerable
# Initialize
enu = [1, 7, 10, 11]
# Prints
enu.select
输出:
Enumerator: [1, 7, 10, 11]:select