需要在Ruby中将数组拆分为指定大小的子数组

bra*_*boy 30 ruby arrays

我有一个类似这样的数组:

arr = [4, 5, 6, 7, 8, 4, 45, 11]
Run Code Online (Sandbox Code Playgroud)

我想要一种奇特的方法

sub_arrays = split (arr, 3)
Run Code Online (Sandbox Code Playgroud)

这应该返回以下内容: [[4, 5, 6], [7,8,4], [45,11]]

Note: This question is not a duplicate of "How to chunk an array" The chunk question is asking about processing in batches and this question is about splitting arrays.

sep*_*p2k 48

arr.each_slice(3).to_a
Run Code Online (Sandbox Code Playgroud)

each_slice returns an Enumerable, so if that's enough for you, you don't need to call to_a.

In 1.8.6 you need to do:

require 'enumerator'
arr.enum_for(:each_slice, 3).to_a
Run Code Online (Sandbox Code Playgroud)

If you just need to iterate, you can simply do:

arr.each_slice(3) do |x,y,z|
  puts(x+y+z)
end
Run Code Online (Sandbox Code Playgroud)

  • 或者`b = []; b << a.shift(3)直到a.empty?`(对于老Rubys) (4认同)

Nic*_*Roz 6

在 Rails 中,您可以使用in_groups_of数组拆分为指定大小的组的方法

arr.in_groups_of(3) # => [[4, 5, 6], [7, 8, 4], [45, 11, nil]]
arr.in_groups_of(3, false) # => [[4, 5, 6], [7, 8, 4], [45, 11]]
Run Code Online (Sandbox Code Playgroud)

而方法in_groups 将数组拆分为指定数量的平衡组

arr.in_groups(5) # => [[4, 5], [6, 7], [8, 4], [45, nil], [11, nil]]
arr.in_groups(5, false) # => [[4, 5], [6, 7], [8, 4], [45], [11]]
Run Code Online (Sandbox Code Playgroud)