Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.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
Arrays Ruby enumerable-查找最多n个匹配元素_Arrays_Ruby - Fatal编程技术网

Arrays Ruby enumerable-查找最多n个匹配元素

Arrays Ruby enumerable-查找最多n个匹配元素,arrays,ruby,Arrays,Ruby,我有以下数组: arr = [1, 3, 2, 5, 2, 4, 2, 2, 4, 4, 2, 2, 4, 2, 1, 5] 我想要一个包含前三个奇数元素的数组 我知道我可以做到: arr.select(&:odd?).take(3) 但我希望避免遍历整个数组,而是在找到第三个匹配项后返回 我提出了以下解决方案,我相信这正是我想要的: my_arr.each_with_object([]) do |el, memo| memo << el if el.odd?; b

我有以下数组:

arr = [1, 3, 2, 5, 2, 4, 2, 2, 4, 4, 2, 2, 4, 2, 1, 5]
我想要一个包含前三个奇数元素的数组

我知道我可以做到:

arr.select(&:odd?).take(3)
但我希望避免遍历整个数组,而是在找到第三个匹配项后返回

我提出了以下解决方案,我相信这正是我想要的:

my_arr.each_with_object([]) do |el, memo| 
  memo << el if el.odd?; break memo if memo.size == 3 
end
my_arr.每个带有对象([])的_都做了什么
备注与以下内容一起使用:

force
用于强制惰性枚举数求值。或者,您可以先使用
,因为它很急切:

arr.lazy.select(&:odd?).first(3)
# => [1, 3, 5]

代码和示例

arr.take_while.with_object([]) do |e,a|
  a << e if e.odd?
  a.size < 3
end
  #=> [1, 3, 5]
获取前10000多个元素:

compare_em(arr, 1e4)
  # Running each test once. Test will take about 1 second.
  # take_while is faster than lazy by 2x ± 1.0
compare_em(arr, 1e5)
  # Running each test once. Test will take about 3 seconds.
  # take_while is faster than lazy by 2x ± 0.1
获得前100000多个元素:

compare_em(arr, 1e4)
  # Running each test once. Test will take about 1 second.
  # take_while is faster than lazy by 2x ± 1.0
compare_em(arr, 1e5)
  # Running each test once. Test will take about 3 seconds.
  # take_while is faster than lazy by 2x ± 0.1

我很惊讶
lazy
做得很好,因为它在基准测试中通常要慢得多。

我确认
force
有效,但除了中的文档外,我找不到其他文档。你知道为什么RDoc的文档中没有它吗?是不是因为它只是
的别名?仅供参考-你可以使用'arr.lazy.select(&:odd?).first(3)`并避免
强制力
-
take
是懒惰的,而
first
不是。@sawa我也找不到它。如果你找到了,请随意编辑我的答案。谢谢。和往常一样,文件似乎不完整。但是你是怎么知道这一点的呢?
Enumerator::Lazy#force
to_a
的别名,它来自
Enumerable
compare_em(arr, 1e5)
  # Running each test once. Test will take about 3 seconds.
  # take_while is faster than lazy by 2x ± 0.1