Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby multiple group_by or map

I searched quite a lot but can't my head around this one.

I have a model which is related to three other models. Let's call it cities. Cities do have a continent, a country and region.

When I select some cities I want to get back an OrderedHash or an array which looks like this:

{ 'Continent 1' => {'Country 1' => { 'Region 1' => { 'City 1', 'City 2' }}}, 'Continent 2' ...}

How can I do this?

like image 366
user1261284 Avatar asked Mar 10 '12 17:03

user1261284


1 Answers

Just group by region:

cities_by_region = City.all(:group => :region)

# set up an automatic 3-level hash...
result = Hash.new { |h,k| h[k] = Hash.new { |h,k| h[k] = {}}}

cities_by_region.each do |region, cities|
  country = region.country
  result[country.continent.name][country.name][region.name] = cities
end

Note that this doesn't employ sorting, but it can be easily adapted to do. Keep in mind that the insertion order of hashes is only retained in Ruby 1.9+.

like image 97
Niklas B. Avatar answered Nov 13 '22 20:11

Niklas B.