假设您有一个这样的有序数组,从地址数据库生成:
[ { city: Sacramento,state: CA },{ city: San Francisco,{ 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方法有任何建议吗?
解决方法
Enumerable#group_by
?
array = [ {city: 'Sacramento',state: 'CA'},{city: 'San Francisco',{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"}]}