加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails Ruby键的哈希值由键合并为平均值

发布时间:2020-12-17 02:47:03 所属栏目:百科 来源:网络整理
导读:我有一个activerecord方法,可以查找本周的所有事件, ?myevents.map {| x | x.start_date.day = [x.title]} (start_date是一个datetime字段,title是一个字符串) 这给了我一系列的哈希; [{11=["40"]},{11=["0"]},{11=[""]},{11=["33"]},{12=["9"]},{11=["34"]}
我有一个activerecord方法,可以查找本周的所有事件,
?myevents.map {| x | x.start_date.day => [x.title]}
(start_date是一个datetime字段,title是一个字符串)
这给了我一系列的哈希;

[{11=>["40"]},{11=>["0"]},{11=>[""]},{11=>["33"]},{12=>["9"]},{11=>["34"]},{11=>["29"]},{11=>["8"]},{11=>["31"]},{11=>["40"]},{11=>["34"]}]

我想映射值,所以我得到一个看起来像的数组;

[ {11=>[ average of values that occur on the 11th]},{12=>[average of values that occur on the 12th]} ]

但我不太清楚如何得到它.

解决方法

我会使用 group_by,injectmap.

ar = [  
        {11=>["40"]},{11=>["34"]}
     ]

# first grouping the inner hash keys like on 11,12,etc. In each iteration,# {11=>["40"]},{11=>["0"]} are being passed to the block of `group_by`. Now
# `h.keys.first` gives 11 from `{11=>["40"]}` and 11 from `{11=>["0"]}` likewise.
ary = ar.group_by { |h| h.keys.first }.map do |k,v|
  { k => v.map { |h| h[k][0].to_i }.inject(:+) / v.size } 
end

ary # => [{11=>19},{12=>9}]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读