There are n news. I want to use Card decks from Bootstrap 4. To do this, I want to group the result of the query into blocks of 3 elements.

But I can not figure out how to do it. Methods of type group_by or group give a completely different result.

Tell me please.

    2 answers 2

    Use the in_groups_of method. It will break your collection into groups of 3 elements each. Example (on slim ):

    - posts.in_groups_of(3).each do |group| .card-deck - group.each do |post| .card .card-block h4.card-title = post.title p.card-text = post.text 

    And if you want to split the collection into 3 groups, use in_groups .

    • Great, thank you. I'd add what I need inside group.each do |post| to do if post.present? , since the void will be filled with null . - Colibri
    • @Colibri in this case, you can use .in_groups_of(3, false) - with the false parameter in your groups there will be no nil-elements. - Vitaly Emelyantsev
    • Well then, in general, infinitely excellent. - Colibri

    In your case, the Enumerable#each_slice method is most likely to work:

     (1..10).each_slice(3) { |a| pa } # outputs below [1, 2, 3] [4, 5, 6] [7, 8, 9] [10] 

    Collections from ActiveRecord (and in many other places!) Contain this module.

    It is only necessary to understand that when calling this method a request will be made for the entire collection, and it will be already in memory to be broken into "slices". But for in_groups_of this is also true ( in_groups_of it is defined only for the array).