3
我需要返回的短切版本匹配
[1, 2, 3, 4, 5, 6, 7, 8].select{|e| e % 2 == 0}
这是[2, 4, 6]
,前三个元素,但不尝试7
和8
。我希望它采取的形式
select_some([1, 2, 3, 4, 5, 6, 7, 8], 3){|e| e % 2 == 0}
我有一个解决办法如下:
def select_some(array, n, &block)
gather = []
array.each do |e|
next unless block.call e
gather << e
break if gather.size >= n
end
gather
end
但有内置到Ruby的东西,执行该短切?请不要建议我在阵列上修补一个方法来实现array.select_some
。
您也可以使用'first(3)'而不是'take(3)'来获得一个数组。 – Stefan
当我检查上述表达式的返回值时,为什么它返回一个枚举数而不是数组?当我使用'first(3)' –
@WandMaker时,它是有效的,因为'take'也是懒惰的。 – Stefan