2015-10-05 55 views
0

我有一個哈希:遍歷散列,只顯示重複的值一次

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

如何刪除與前一個循環中的值相同的值?

回答

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