简体   繁体   中英

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]

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>

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 %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM