4 } 我需要的是一个包含 n-6ren">
gpt4 book ai didi

ruby - 如何在 Ruby 中分隔数组?

转载 作者:太空宇宙 更新时间:2023-11-03 17:17:16 25 4
gpt4 key购买 nike

好的,所以我有一个数组:

numbers = ["2", "3", "4", "5"]

我需要用条件将数组拆分成两个数组

numbers.reject!{|x| x > 4 }

我需要的是一个包含 numbers = ["5"] 的数组 numbers 和另一个包含 rejects rejects = ["2", “3”、“4”]

我该怎么做? ...使用循环似乎很容易,但有没有办法在一个衬里中做到这一点?

最佳答案

查看 Enumerable#partition

arr = ["2", "3", "4", "5"]
numbers, rejects = arr.partition{ |x| x.to_i > 4 }
# numbers = ["5"]
# rejects = ["2", "3", "4"]

关于ruby - 如何在 Ruby 中分隔数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11959110/

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