rap*_*tle 4 ruby arrays hash ruby-on-rails
我有一个activerecord方法,可以查找本周的所有事件,
myevents.map { |x| x.start_date.day => [x.title]}
(start_date是一个日期时间字段,标题是一个字符串),它给了我一个哈希数组;
[{11=>["40"]}, {11=>["0"]}, {11=>["0"]}, {11=>[""]},
{11=>["0"]}, {11=>["0"]}, {11=>["33"]}, {12=>["9"]},
{11=>["34"]}, {11=>["29"]}, {11=>["8"]}, {11=>["31"]},
{11=>["40"]}, {11=>["34"]}]
Run Code Online (Sandbox Code Playgroud)
我想映射值,所以我得到一个看起来像的数组;
[ {11=>[ average of values that occur on the 11th]},
{12=>[average of values that occur on the 12th]} ]
Run Code Online (Sandbox Code Playgroud)
但我不太清楚如何得到它.
ar = [
{11=>["40"]}, {11=>["0"]}, {11=>["0"]}, {11=>[""]},
{11=>["0"]}, {11=>["0"]}, {11=>["33"]}, {12=>["9"]},
{11=>["34"]}, {11=>["29"]}, {11=>["8"]}, {11=>["31"]},
{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}]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1301 次 |
| 最近记录: |