Search code examples
rubymiddleman

Sort ruby middleman array into 3 columns, content in placed in order to display LTR


I am using middleman and have a specific structure that I want my articles to fall into:

.row>
  .col-1>article 1, article 4...
  .col-2>article 2, article 5...
  .col-3>article 3, article 6...

The goal is that the articles read left-to-right, however are stacked in their columns so there is now additional row class that is needed. I have these articles enclosed in a visual card, and want to stack them which is why I have this strange problem to solve.

My question is what is the cleanest ruby way to sort the array into this format? The goal is to use it in a structure like this and be able to account for any number of columns, n.

.row
  - page_articles.someProcess(n).each_split(n) do | col |
    .column-class
      - col.each do | art |
         ...

Solution

  • Verbatim from group_by doc:

    (1..6).group_by{ |i| i%3 }
        #=> {0=>[3, 6], 1=>[1, 4], 2=>[2, 5]}
    

    specifically, use the flatten values

    page_articles.group_by.with_index{ |a,i| i%3 }.values.flatten(1)