如何从Ruby数组中选择满足条件的前n个元素?

4
我想从一个数组中获取所有满足条件的元素,一旦遇到不符合条件的元素,我应该停止迭代。例如:
[1, 4, -9, 3, 6].select_only_first { |x| x > 0}

我期望得到:[1, 4] 的结果。

熟悉数组和可枚举对象上的所有方法是很好的。这将为您节省大量时间! - Mark Thomas
3个回答

6
这是您想要的方式:
arup@linux-wzza:~> pry
[1] pry(main)> [1, 4, -9, 3, 6].take_while { |x| x > 0}
=> [1, 4]
[2] pry(main)>

这里是文档:
arup@linux-wzza:~> ri Array#take_while

= Array#take_while

(from ruby site)
------------------------------------------------------------------------------
  ary.take_while { |arr| block }  -> new_ary
  ary.take_while                  -> Enumerator

------------------------------------------------------------------------------

Passes elements to the block until the block returns nil or false, then stops
iterating and returns an array of all prior elements.

If no block is given, an Enumerator is returned instead.

See also Array#drop_while

  a = [1, 2, 3, 4, 5, 0]
  a.take_while { |i| i < 3 }  #=> [1, 2]


lines 1-20/20 (END)

1

如果您正在探索其他解决方案,这也可以起作用:

[1, 4, -9, 3, 6].slice_before { |x| x <= 0}.to_a[0]

你需要将 x > 0 改为 x <= 0。

你可以将 to_a[0] 替换为 first - Cary Swoveland

0

阿鲁普,你的回答非常好。我的方法稍微有点复杂。

numbers = [1,4,-9,3,6]

i = 0
new_numbers = []
until numbers[i] < 0
  new_numbers.push(numbers[i])
  i+= 1
end

=> [1,4]

这并不是 Ruby/函数式编程的正确方式。Ruby 的设计初衷就是要优雅。 - David T.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接