简体   繁体   English

如何按日期组合数组和哈希

[英]How to combine array and hash by date

I have an array and a hash. 我有一个数组和一个哈希。 The array contains dates and the hash contains a date as key and a float as value (revenue_green). 该数组包含日期,散列包含日期作为键和浮点数作为值(revenue_green)。

This is my array: 这是我的数组:

@reporting_dates = @month_ends.find_all {|e| e < @current_reporting_date.to_s } <<
  @current_reporting_date

And my hash: 而我的哈希:

@revenue_green = @reports_at_reporting_dates.sum('revenue_green')

Which gives me the following output: 这给了我以下输出:

@reporting_dates: ["2017-01-27", "2017-02-24", Fri, 10 Mar 2017]
@revenue_green: {Fri, 10 Mar 2017=>7.0}

For two dates of @reporting_dates (2017-01-27 and 2017-02-24) @revenue_green does not have any values. 对于@reporting_dates两个日期(2017-01-27和2017-02-24), @revenue_green没有任何值。

I want to create a hash that gives me the following output: 我想创建一个散列,为我提供以下输出:

@new_hash: {2017-01-27 => 0, 2017-02-24 => 0, 2017-03-10 => 7.0}

so for all dates where no revenue_green exists it should put a 0. 因此,对于所有不存在revenue_green日期,都应将其设置为0。

How can I do that? 我怎样才能做到这一点?

UPDATE 更新

@month_ends = ["2017-01-27", "2017-02-24", "2017-03-31", "2017-04-28",
               "2017-05-26", "2017-06-30", "2017-07-28", "2017-08-25",
               "2017-09-29", "2017-10-27", "2017-11-24", "2017-12-29"]

@all_dates = (Date.new(@reporting_year).
  beginning_of_year..1.month.from_now).
  to_a.reverse.select { |day| day.wday == 5 }

@current_reporting_date = @all_dates.select { |d| d <= Date.today }.first

@all_reports = Report.all

@reports_at_reporting_dates = @all_reports.where(:day => @reporting_dates).order(:day)

Assuming your starting objects are 假设您的起始对象是

@reporting_dates = ["2017-01-27", "2017-02-24", "Fri, 10 Mar 2017"]
@revenue_green = {"Fri, 10 Mar 2017"=>7.0}

(ie, quotes around "Fri, 10 Mar 2017"), then this should work: (即,“ 2017年3月10日,星期五”附近的引号),则此方法应该有效:

require 'date'
@new_hash = Hash.new
@reporting_dates.each {|d| @new_hash[Date.parse(d)] = @revenue_green[d] || 0}

@new_hash => {#<Date: 2017-01-27 ((2457781j,0s,0n),+0s,2299161j)>=>0, #<Date: 2017-02-24 ((2457809j,0s,0n),+0s,2299161j)>=>0, #<Date: 2017-03-10 ((2457823j,0s,0n),+0s,2299161j)>=>7.0}

or, if you want the keys in the new hash to be strings, 或者,如果您希望新哈希中的键为字符串,

@reporting_dates.each {|d| @new_hash[Date.parse(d).strftime("%Y-%m-%d")] = @revenue_green[d] || 0}

@new_hash => {"2017-01-27"=>0, "2017-02-24"=>0, "2017-03-10"=>7.0}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM