获取嵌套元素的频率,并保留关系

发布于 2024-11-27 22:31:43 字数 510 浏览 2 评论 0原文

数组

  • 我有一个

    shop 对象

    • 属于城市对象

      • 属于县对象

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

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

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
}

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

I have an array of

  • shop objects

    • which belong to city objects

      • which belong to prefecture objects

I'd like to end up with a hash listed by prefecture, then city, then frequency...

I came up with this, but it feels really un-rubylike..

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
}

There must be a DRY-er way to do this !

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

深居我梦 2024-12-04 22:31:43
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
}
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
}
清风挽心 2024-12-04 22:31:43
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}}
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}}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文