Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
“的内置Ruby或ActiveSupport函数”;选择满足谓词“quot;”的前n个元素;?_Ruby_Activesupport - Fatal编程技术网

“的内置Ruby或ActiveSupport函数”;选择满足谓词“quot;”的前n个元素;?

“的内置Ruby或ActiveSupport函数”;选择满足谓词“quot;”的前n个元素;?,ruby,activesupport,Ruby,Activesupport,我正在寻找一个select,它在返回一定数量的项目后会“短路”: >>> [1, 2, 3, 4, 5].select_first(1) { |x| x.odd? } [1] >>> [1, 2, 3, 4, 5].select_first(2) { |x| x.odd? } [1, 3] >>> [1, 2, 3, 4, 5].select_first(1000) { |x| x.odd? } [1, 3, 5] core或ActiveS

我正在寻找一个
select
,它在返回一定数量的项目后会“短路”:

>>> [1, 2, 3, 4, 5].select_first(1) { |x| x.odd? }
[1]
>>> [1, 2, 3, 4, 5].select_first(2) { |x| x.odd? }
[1, 3]
>>> [1, 2, 3, 4, 5].select_first(1000) { |x| x.odd? }
[1, 3, 5]
core或ActiveSupport中是否有库函数可以实现这一点?我自己滚很容易,但我想我会检查一下


请注意,我不希望
选择{…}。采用(n)
,因为该块可能有副作用。

您可以按照

[1, 2, 3, 4, 5].lazy.select{|x| x.odd? }.take(n).to_a
但是如果您想避免
选择{..}.take(n)
,您也可以这样做:

[1, 2, 3, 4, 5].each{|x| arr << x if x.odd?; break if arr.count == n}

[1,2,3,4,5]。每一个{code>x{arr,你担心什么样的副作用?如果你使用
first(n)
而不是
take(n)
你可以取消
to_a
第二个例子,我相信你的意思是
arr.count
因为
x
是一种
Fixnum
方法,没有
count
方法。