Reputation: 1181
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).
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.
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.
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)
Upvotes: 0
Views: 143
Reputation: 1380
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}
(i.e., quotes around "Fri, 10 Mar 2017"), then this should work:
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}
Upvotes: 1