我有一个哈希:
@table = [
{"country" => "england", "home" => "team a", "away" => "team b"},
{"country" => "england", "home" => "team c", "away" => "team d"}
]
我想:
<div class="row">
england
</div>
<div class="row">
team a vs team b
</div>
<div class="row">
team c vs team d
</div>
我运行了这段代码:
<% table.each do |table| %>
<div class="row">
<%= table["country"] %>
</div>
<div class="row">
<%= table["home"] vs table["away"] %>
</div>
<% end %>
结果是:
<div class="row">
england
</div>
<div class="row">
team a vs team b
</div>
<div class="row">
england
</div>
<div class="row">
team c vs team d
</div>
如何删除与前一循环中的值相同的值?
答案 0 :(得分:2)
您可以使用Enumerable#group_by
:
@country_table = @table.group_by { |i| i['country'] }
然后你可以:
@country_table.each do |country, matches|
puts country
puts matches.map { |_, v| v.values_at('home', 'away').join(' vs ') }
end