循环遍历ruby(rails)中的分组数据数组

时间:2011-03-23 21:27:50

标签: ruby-on-rails ruby

假设您有一个这样的有序数组,它是从地址数据库生成的:

[
  { city: Sacramento, state: CA },
  { city: San Francisco, state: CA },
  { city: Seattle, state: WA }
]

你想用它生成HTML:

<p>CA</p>
<ul>
    <li>Sacramento</li>
    <li>San Francisco</li>
</ul>
<p>WA</p>
<ul>
    <li>Seattle</li>
</ul>

所以你按州分组。这样做的一种方法是记住循环的每次迭代的最后一行,并且仅当当前行的状态与最后行状态相同时才显示状态和bookending UL标记。这看起来很讨厌,非Ruby-y。

任何人对优雅的Ruby / Rails方法都有任何建议?

3 个答案:

答案 0 :(得分:8)

Enumerable#group_by

array = [
  {city: 'Sacramento', state: 'CA'},
  {city: 'San Francisco', state: 'CA'},
  {city: 'Seattle', state: 'WA'}
]

array.group_by{|elem| elem[:state]}
# => {"CA"=>[{:city=>"Sacramento", :state=>"CA"}, {:city=>"San Francisco", :state=>"CA"}], "WA"=>[{:city=>"Seattle", :state=>"WA"}]} 

答案 1 :(得分:8)

Enumerablegroup_by

cities = [
  { city: "Sacramento", state: "CA" },
  { city: "San Francisco", state: "CA" },
  { city: "Seattle", state: "WA" }]

cities.group_by {|c| c[:state]}


=> {"CA"=>[{:city=>"Sacramento", :state=>"CA"}, 
           {:city=>"San Francisco", :state=>"CA"}], 
    "WA"=>[{:city=>"Seattle", :state=>"WA"}]}

我在ERB上有点生疏,但我认为它会是这样的

<% @cities_by_state.each do |state, cities| %>
<p><%= state %></p>
<ul>
  <% cities.each do |city| %>
    <li><%= city[:city] %></li>
  <% end %>
</ul>
<% end %>

答案 2 :(得分:0)

您可以在Rails中使用group_by函数

@records.group_by{|x| x[:state]}

这将返回一个哈希,其中键是状态,值是记录数组

This link应该可以帮助你弄清楚它是如何运作的。