[英]Ruby, Array.select with number of elements
I have this array 我有这个数组
[1, 2, 3, 4, 5, 6]
I would like to get the first 2 elements that are bigger than 3. 我想获得大于3的前2个元素。
I can do: 我可以:
elements = []
[1, 2, 3, 4, 5, 6].each do |element|
elements << element if element > 3
break if elements.size == 2
end
puts elements
Is there a more elegant way to do this? 有没有更优雅的方法可以做到这一点?
Is there something in the Ruby core like Array.select(num_elements, &block)
? 在Ruby核心中是否有类似
Array.select(num_elements, &block)
?
a = [1, 2, 3, 4, 5, 6]
p a.filter {|x| x > 3}.first(2)
Or 要么
p a.select{|x| x > 3}.first(2)
output 输出
[4, 5]
As Cary suggest, the given below code wouldn't be a performance hit if array is bigger, it would stop executing further if 2 elements are found 正如卡里(Cary)所建议的,如果数组较大,下面给出的代码不会对性能造成影响,如果找到2个元素,它将停止进一步执行
a.lazy.select{|x| x > 3}.first(2)
You were nearly there. 你快到了 Just use
break
with a parameter: 只需使用带有参数的
break
:
[1, 2, 3, 4, 5, 6].each_with_object([]) do |element, acc|
acc << element if element > 3
break acc if acc.size >= 2
end
Another way to accomplish it, would be to use Enumerator::Lazy
with array.lazy.select
, or an explicit Enumerator
instance with Enumerable#take
(here it's a definite overkill, posting mostly for educational purposes.) 实现它的另一种方法是将
Enumerator::Lazy
与array.lazy.select
一起使用,或者将一个显式的Enumerator
实例与Enumerable#take
(这是绝对的过大杀伤力,主要是出于教育目的而发布)。
enum =
Enumerator.new do |y|
i = [1, 2, 3, 4, 5, 6].each
loop { i.next.tap { |e| y << e if e > 3 } }
end
enum.take(2)
#⇒ [4, 5]
Sidenote: both examples above would stop traversing the input as soon as two elements are found. 旁注:一旦找到两个元素,以上两个示例都将停止遍历输入。
Just for having a couple of options more.. 只是为了有更多选择。
ary.each_with_object([]) { |e, res| res << e if e > 3 && res.size < 2 }
or 要么
ary.partition { |e| e > 3 }.first.first(2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.