Home > Enterprise >  How to iterate over an array of hashes? (ruby)
How to iterate over an array of hashes? (ruby)

Time:09-08

How do I iterate over an array of hashes, so that I get the following type of list:

title[0]
-----
description[0]

description[1]

title[1]
-----
description[2]

description[3]
@example = 
[
  {title: "chapter1", description: "Hello all"}, 
  {title: "chapter1", description: "This is an example"},
  {title: "chapter2", description: "This is chapter 2"}, 
  {title: "chapter2", description: "Another example"}, 
]
<% @example.each_with_index do |item, index| %>
       <h1><%= item[:title] %></h1>
       <p><%= item[:description] %></p>
<% end %>

How do I modify the above code so that if item[:title] == "chapter1", then it loops over the descriptions, and after that it goes through item[:title] == "chapter2" descriptions? I would like to show only the descriptions that belong to the title. Do I have to use a case...when statement, or is there a nicer way to do it?

To use the above example, I would like it to be:

<h1>Chapter 1</h1>
<p>Hello all</p>
<p>This is an example</p>

<h1>Chapter 2</h1>
<p>This is chapter 2</p>
<p>Another example</p>

CodePudding user response:

You can achieve this by using group_by:

<% @example.group_by{|item| item[:title]}.each do |title,array| %>
    <h1><%= title %></h1>
    <% array.each do |item| %>
        <p><%= item[:description] %></p>
    <% end %>
<% end %>
  • Related