Q:

Group by category loop - rails

I'm trying to create a loop that will group together the cards in an array by the category, and then create a carousel for each one, with the cards (in that category) as the images.
Below is my attempt, the inside loop works but it just shows all of the cards in one carousel. I can't work out how to make it group by category.. 
<% @cards.group_by(:categories).each do |c| %>

    <h2><%= c["categories"] %></h2>

    <div id="myCarousel" class="carousel slide" data-interval="false">

        <!-- Carousel items -->
        <div class="carousel-inner">
            <div class="item active">
                <div>

                    <% @cards.each_with_index do |p, i| %>

                    <div class="span3">

                        <a href="#"><img src=<%= p["url"] %> alt="" class="img-responsive"></a>

                    </div>
                    <% if ((i+1) % 4) == 0 %>

                </div>
                <!--/row-->
            </div>
            <!--/item-->
            <div class="item">
                <div>

                    <%end%>
                    <%end%>

                </div>
                <!--/carousel-inner-->

              </div>
              <!--/myCarousel-->

            </div>
            <a class="left carousel-control" href="#myCarousel" data-slide="prev">‹</a>

            <a class="right carousel-control" href="#myCarousel" data-slide="next">›</a>

         </div>
         <%end%>

The array:
@cards = [{"url"=>"BB08-74C2-6C06-43CD-385B.jpg", "categories"=>"Birthday", "desc"=>"9 - Orange/Purple Dotty"}... 

A:

You were almost there!
Here is the right syntax to use with group_by:
<% @cards.group_by { |card| card['categories'] }.each do |category, cards| %>
  <h2><%= category %></h2>
  # etc.

  <% cards.each_with_index do |p, i| %>
    # your view to display each card
  <% end %>

  # etc.
<% end %>

group_by() method will group an array on each uniq object returned by the block you gave it, examples:
['Alice', 'John', 'Alex'].group_by do |element| 
  element[0] # returns the first letter of the string
end
# returns
{ 'A' => ['Alice', 'Alex'],
  'J' => ['John'] }

# this instruction
@cards.group_by(&:category)
# is a shorthand for the long-version
@cards.group_by { |card| card.category }

