gpt4 book ai didi

Ruby:总结特定日期之间哈希数组中的值

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

我在 Ruby 中有一个哈希数组:

array = [
{:date => Wed, 04 May 2011 00:00:00 PDT -07:00,
:value => 200}
{:date => Wed, 04 May 2011 01:00:00 PDT -07:00,
:value => 100}
{:date => Tue, 03 May 2011 01:00:00 PDT -07:00,
:value => 300}
{:date => Tue, 03 May 2011 01:00:00 PDT -07:00,
:value => 150}
]

我希望能够合并每一天的值,这样我就有了一个像这样的新数组:

array = [
{:date => Wed, 04 May 2011 00:00:00 PDT -07:00,
:value => 300}
{:date => Tue, 03 May 2011 00:00:00 PDT -07:00,
:value => 450}
]

按天搜索数组并对每一天的值求和的最优雅的方法是什么?

这是我最初尝试的:

entries = [
{:date => Wed, 04 May 2011 00:00:00 PDT -07:00,
:value => 200}
{:date => Wed, 04 May 2011 01:00:00 PDT -07:00,
:value => 100}
{:date => Tue, 03 May 2011 01:00:00 PDT -07:00,
:value => 300}
{:date => Tue, 03 May 2011 01:00:00 PDT -07:00,
:value => 150}
]

first_day = 29.days.ago.beginning_of_day
total_days = 30

day_totals = (0...total_days).inject([]) do |array, num|
startat = first_day + num.day
endat = startat.end_of_day

total_value_in_day = entries.where("date >= ? and date <= ?", startat, endat).sum(:value)

array << {:date => startat, :value => total_value_in_day}
end

我意识到我的错误在于 where 方法,这是一种用于搜索对象的 Rails 方法,不能用于数组。所以我的主要问题是,有没有一种方法可以根据条件搜索数组或散列。

最佳答案

您可以遍历条目以创建一个新数组:

totals = Hash.new(0)
array.each do |entry|
totals[entry[:date]] += entry[:value]
end

# Now totals will be something like this:
# => {"Wed, 04 May 2011" => 300, "Tue, 03 May 2011" => 450...}

# If you then want this in the same array format you started with:
new_array = totals.collect{ |key, value| {:date => key, :value => value} }
# => [{:date => "Wed, 04 May 2011", :value => 300}, {....}]

关于Ruby:总结特定日期之间哈希数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5889589/

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