1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| def group_by_kana(zip_codes, column) return zip_codes unless zip_codes[0].respond_to? column key = %w(ア カ サ タ ナ ハ マ ヤ ラ ワ) zip_codes.group_by do |zip_code| key[key.index{|i| i > zip_code.send(column)[0]}.to_i - 1] end end
zip_codes = ZipCode.where(state_code: 13).group(:city_code).limit(5)
group_by_kana(zip_codes, :city_kana)
{"タ"=> [#<ZipCode code: "1000000", state_code: 13, state: "東京都", state_kana: "トウキョウト", city_code: 13101, city: "千代田区", city_kana: "チヨダク", town_code: 131010000, town: nil, town_kana: nil, special: true, created_at: "2016-01-15 08:50:43", updated_at: "2016-01-18 04:20:35">, "マ"=> [#<ZipCode code: "1050000", state_code: 13, state: "東京都", state_kana: "トウキョウト", city_code: 13103, city: "港区", city_kana: "ミナトク", town_code: 131030000, town: nil, town_kana: nil, special: true, created_at: "2016-01-15 08:50:50", updated_at: "2016-01-18 04:20:37">], "サ"=> [#<ZipCode code: "1600000", state_code: 13, state: "東京都", state_kana: "トウキョウト", city_code: 13104, city: "新宿区", city_kana: "シンジュクク", town_code: 131040000, town: nil, town_kana: nil, special: true, created_at: "2016-01-15 08:50:54", updated_at: "2016-01-18 04:20:40">], "ハ"=> [#<ZipCode code: "1120000", state_code: 13, state: "東京都", state_kana: "トウキョウト", city_code: 13105, city: "文京区", city_kana: "ブンキョウク", town_code: 131050000, town: nil, town_kana: nil, special: true, created_at: "2016-01-15 08:50:58", updated_at: "2016-01-18 04:20:41">]}
|