I have a hash
{"Apr 2016"=>6.0, "Aug 2016"=>7.5, "Jan 2017"=>8.666666666666666, "Apr 2017"=>7.333333333333333, "May 2017"=>7.571428571428571, "Jun 2017"=>6.75, "Jul 2017"=>6.7272727272727275}
I want display a chart line but the empty months in my hash create ugly chart, I would know how get empty months and give previous value has value to get something like
{"Apr 2016"=>6.0, "May 2016"=>6, "June 2016"=>6, "July 2016"=>6 "Aug 2016"=>7.5, "Jan 2017"=>8.666666666666666...}
UPDATE: I get all values but i dont know how atribute the previous value when the value is empty, i tried many things but nothing work
Please read the Update as well.
You will need to fill the gaps:
This creates a date range with start and end date and then iterates it. It creates a String from the date (
strftime
) and checks if it is already in the hash (||=
) and if not, assigns it with value set to0
Depending on how you render the chart and what you actually want to display,0
might be the wrong value, perhaps you'll need to set it tonil
.UPDATE: I just realized that this is not the most efficient way to do this because the range will contain a entry per day, not per month. I'll leave the code in the answer but you should use something like:
Code
Example
Explanation
See Date::strptime, Date#strftime, Date#>>, Enumerable#minmax and Hash#fetch.
Let's go though the steps for
h
given in the example.Perform the loop calculation once
Now proceed through the loop once more.
This time
fetch
uses its default (last #=> 6.0
) becauseh
has no key"Jun 2016"
.The remaining calculations are similar.