2

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 = [] %>
<% @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 Answer 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.

final_array = []
a.each_slice(3) do |slice|
   final_array << slice
end
# or
final_array = a.each_slice(3).inject([]) { |arr, slice| arr << slice }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.