gpt4 book ai didi

ruby - 如何从满足谓词的 Ruby 数组中选择前 n 个元素?

转载 作者:数据小太阳 更新时间:2023-10-29 07:26:58 24 4
gpt4 key购买 nike

我想从数组中获取满足谓词的所有项。一旦我看到一个不满足的元素,我就应该停止迭代。例如:

[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)

关于ruby - 如何从满足谓词的 Ruby 数组中选择前 n 个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25168005/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com