Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

title[0]

description[0]

description[1]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>

>Solution :

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 %>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading