gpt4 book ai didi

ruby - 在ruby中按固定长度分割数组

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

<分区>

Possible Duplicate:
Need to split arrays to sub arrays of specified size in Ruby

按给定长度分割数组的最佳方法是什么?我想要的是下面的“segment_by”之类的东西:

[1, 2, 3, 4, 5, 6].segment_by(2)
# => [[1, 2], [3, 4], [5, 6]]

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'].segment_by(3)
# => [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]

我设法想出的是以下内容,但看起来不够简单:

class Array
def segment_by i
(0...length).group_by{|x| x.div(i)}.values.map{|a| a.map{|j| self[j]}}
end
end

我正在使用 ruby​​1.9.2。是否已经有这样的方法,还有更好的方法吗?

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