Ruby - 通过循环创建按位置分组的数组数组

时间:2021-10-22 12:54:31

I have the following loop that renders an array "a" of arrays. Each arrays is defined by an index (the position of the image) and the image_id

我有以下循环呈现数组“a”的数组。每个数组由索引(图像的位置)和image_id定义

<% a = [] %>
<% @portfolio_entry.images.each_with_index do |image, index| %>
  <% a << [index, image.id] %>
<% end %>
<%= a %>

here's an example of the output:

这是输出的一个例子:

[[0, 2], [1, 1], [2, 1], [3, 2], [4, 1], [5, 1], [6, 3]] 

What I want to create is a loop which can group arrays of the first three images positions, then the next three etc... in a "final" array (as my english is so-so please see the example I want to achieve:)

我想要创建的是一个循环,它可以将前三个图像位置的数组,然后接下来的三个等等...放在一个“最终”数组中(因为我的英语是马马虎虎,请参阅我想要实现的示例: )

Finalarray => [array1, array2, array3]

array1 => [[0, 2], [1, 1], [2, 1]]        # position 0,1,2
array2 => [[3, 2], [4, 1], [5, 1]]        # position 3,4,5
array3 => [[6, 3]]                        # position 6

I tried to figure out how I can do this (collect?) but without any concrete result.

我试图找出我怎么做(收集?)但没有任何具体结果。

Thanks for any idea!

谢谢你的任何想法!

1 个解决方案

#1


4  

a = [[0, 2], [1, 1], [2, 1], [3, 2], [4, 1], [5, 1], [6, 3]] 
array1, array2, array3 = a.each_slice(3).to_a
array1 # => [[0, 2], [1, 1], [2, 1]]
array2 # => [[3, 2], [4, 1], [5, 1]]
array3 # => [[6, 3]]

Edit: if you need more arrays, leave of the to_a call and deal with the slices in the block.

编辑:如果您需要更多数组,请离开to_a调用并处理块中的切片。

final_array = []
a.each_slice(3) do |slice|
   final_array << slice
end
# or
final_array = a.each_slice(3).inject([]) { |arr, slice| arr << slice }

#1


4  

a = [[0, 2], [1, 1], [2, 1], [3, 2], [4, 1], [5, 1], [6, 3]] 
array1, array2, array3 = a.each_slice(3).to_a
array1 # => [[0, 2], [1, 1], [2, 1]]
array2 # => [[3, 2], [4, 1], [5, 1]]
array3 # => [[6, 3]]

Edit: if you need more arrays, leave of the to_a call and deal with the slices in the block.

编辑:如果您需要更多数组,请离开to_a调用并处理块中的切片。

final_array = []
a.each_slice(3) do |slice|
   final_array << slice
end
# or
final_array = a.each_slice(3).inject([]) { |arr, slice| arr << slice }