我有以下数组:
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
但是有没有更简单/惯用的方法来做到这一点?
最佳答案
使用 lazy enumerator与 Enumerable#lazy :
arr.lazy.select(&:odd?).take(3).force
# => [1, 3, 5]
force
用于强制惰性枚举器求值。或者,您可以使用 first
,因为它很急切:
arr.lazy.select(&:odd?).first(3)
# => [1, 3, 5]
关于arrays - Ruby 可枚举 - 查找最多 n 次匹配元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32857049/