我想从数组中获取所有项目,这些项目满足谓词。一旦我看到一个不满足的元素,我应该停止迭代。例如:
[1, 4, -9, 3, 6].select_only_first { |x| x > 0}
我期待得到:[1, 4]
答案 0 :(得分: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)
如果你正在探索其他解决方案,这也有效:
[1, 4, -9, 3, 6].slice_before { |x| x <= 0}.to_a[0]
你必须改变x&gt; 0到x <= 0。
答案 2 :(得分:0)
Arup是一个很好的答案。我的方法稍微复杂一些。
numbers = [1,4,-9,3,6]
i = 0
new_numbers = []
until numbers[i] < 0
new_numbers.push(numbers[i])
i+= 1
end
=> [1,4]