如何遍歷哈希陣列,以便獲得以下型別的串列:
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 %>
如何修改上面的代碼if item[:title] == "chapter1"
,然后回圈遍歷描述,然后遍歷item[:title] == "chapter2"
描述?我只想顯示屬于標題的描述。我必須使用case...when
宣告,還是有更好的方法?
要使用上面的示例,我希望它是:
<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>
uj5u.com熱心網友回復:
您可以使用以下方法實作此目的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 %>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/507584.html
上一篇:如何使用GoogleAPIDrivev3ruby??gem將檔案上傳到共享驅動器
下一篇:在Ruby中決議哈希