我有一个月的散列->值
{"Apr 2016"=>6, "Aug 2016"=>9, "Jan 2017"=>11, "Apr 2017"=>6, "May 2017"=>9, "Jun 2017"=>1, "Jul 2017"=>9}
我知道什么是从第一个月到最后一个月之间得到所有空月的最好方法
我想要一些像
{"Apr 2016"=>6, May 2016=>0, Jun 2016=>0 .... "Aug 2016"=>9, "Sep 2016" => 0 "Jan 2017"=>11, "Apr 2017"=>6, "May 2017"=>9, "Jun 2017"=>1, "Jul 2017"=>9}
最佳答案
还有一种方法,使用each_with_object
:
def add_months(dates)
min, max = dates.keys.map { |date| Date.parse(date) }.minmax
range = (min..max).map { |date| date.strftime("%b %Y") }.uniq
range.each_with_object({}) { |date, result| result[date] = dates[date] || 0 }
end
输出:
dates = {"Apr 2016"=>6, "Aug 2016"=>9, "Jan 2017"=>11, "Apr 2017"=>6, "May 2017"=>9, "Jun 2017"=>1, "Jul 2017"=>9}
add_months(dates)
#=> {
# "Apr 2016"=>6,
# "May 2016"=>0,
# "Jun 2016"=>0,
# "Jul 2016"=>0,
# "Aug 2016"=>9,
# "Sep 2016"=>0,
# "Oct 2016"=>0,
# "Nov 2016"=>0,
# "Dec 2016"=>0,
# "Jan 2017"=>11,
# "Feb 2017"=>0,
# "Mar 2017"=>0,
# "Apr 2017"=>6,
# "May 2017"=>9,
# "Jun 2017"=>1,
# "Jul 2017"=>9
# }