获取嵌套元素的频率,并保留关系
数组
- 我有一个
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)