我想从一个数组中获取所有满足条件的元素,一旦遇到不符合条件的元素,我应该停止迭代。例如:
我期望得到:
[1, 4, -9, 3, 6].select_only_first { |x| x > 0}
我期望得到:
[1, 4]
的结果。[1, 4, -9, 3, 6].select_only_first { |x| x > 0}
[1, 4]
的结果。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, 4, -9, 3, 6].slice_before { |x| x <= 0}.to_a[0]
to_a[0]
替换为 first
。 - Cary Swoveland阿鲁普,你的回答非常好。我的方法稍微有点复杂。
numbers = [1,4,-9,3,6]
i = 0
new_numbers = []
until numbers[i] < 0
new_numbers.push(numbers[i])
i+= 1
end
=> [1,4]