gpt4 book ai didi

ruby-on-rails - Rails Ruby 哈希数组按键合并为平均值

转载 作者:数据小太阳 更新时间:2023-10-29 07:27:01 25 4
gpt4 key购买 nike

我有一个 activerecord 方法可以找到一周的所有事件, myevents.map { |x| x.start_date.day => [x.title]}(start_date 是日期时间字段,title 是字符串)这给了我一个哈希数组;

    [{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"]}]

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

[ {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=>["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}]

关于ruby-on-rails - Rails Ruby 哈希数组按键合并为平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22348960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com