Loop through an array of grouped data in ruby ​​(rails)

Say you have an ordered array like this generated from an address database:

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

And you want to generate HTML this way:

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

So you are grouped by state. One way to do this is to remember the last line in each iteration of the loop and display UL status and book tags only if the current state of the line matches the state of the last lines. This seems like nasty and not Ruby-y.

Anyone have any tips on the elegant Ruby / Rails approach?

+6
ruby ruby-on-rails
source share
3 answers

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"}]} 
+8
source share

Enumerable has group_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"}]} 

I'm a little rusty on ERB, but I think it will be something like this

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

You can use the group_by function in Rails

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

This will return a hash where the key is state and the values ​​are an array of records

This link should help you figure out how it works a little more.

0
source share

All Articles