0

我有一个数组

  • 商店物品

    • 属于城市对象

      • 属于地府对象

我想得到一个按县列出的哈希,然后是城市,然后是频率......

我想出了这个,但感觉真的不像红宝石..

city_by_prefecture = shop_list.reduce({}){ |h,e|
  if h[e.prefecture.name].nil?
    h[e.prefecture.name] = {e.city.name => 1}
  elsif h[e.prefecture.name][e.city.name].nil?
    h[e.prefecture.name][e.city.name] = 1
  else
    h[e.prefecture.name][e.city.name] += 1
  end
  h
}

必须有一种干燥的方法来做到这一点!

4

2 回答 2

1
city_by_prefecture = shop_list.each_with_object({}){ |e,h|
  h[e.prefecture.name] ||= Hash.new(0)
  h[e.prefecture.name][e.city.name] += 1
}
于 2011-08-02T08:40:55.137 回答
0
shops = [
  OpenStruct.new(:prefacture => "pre1", :city => "city1"), 
  OpenStruct.new(:prefacture => "pre1", :city => "city1"), 
  OpenStruct.new(:prefacture => "pre1", :city => "city2"), 
  OpenStruct.new(:prefacture => "pre2", :city => "city3"),
]

counts = Hash[shops.group_by(&:prefacture).map do |prefacture, shops_in_prefacture| 
  [prefacture, Hash[shops_in_prefacture.group_by(&:city).map do |city, shops_in_city| 
    [city, shops_in_city.size]
   end]] 
end]
# {"pre1"=>{"city1"=>2, "city2"=>1}, "pre2"=>{"city3"=>1}}
于 2011-08-02T08:49:51.423 回答