Ruby日期范围为Hash

时间:2013-12-05 15:12:13

标签: ruby-on-rails ruby

我正在尝试输入:

1.week.ago.to_date..Date.today

这样的事情:

{ 0 => '5/6', 1 => '5/15', 2 => '5/24', 3 => '5/30', 4 => '6/4',
             5 => '6/12', 6 => '6/21', 7 => '6/28' }

我有什么想法可以做到这一点?

3 个答案:

答案 0 :(得分:1)

一点点清洁

h = {}
(1.week.ago.to_date..Date.today).each {|x| h[h.count] = x.strftime("%m/%d")}

h # => {0=>"11/28", 1=>"11/29", 2=>"11/30", 3=>"12/01", 4=>"12/02", 5=>"12/03", 6=>"12/04", 7=>"12/05"}

答案 1 :(得分:0)

考虑到约会,您可以执行以下操作:

p Hash[(0..7).map{|day| [day, (Date.today+day*7).strftime('%m/%d')]}] #=> {0=>"12/05", 1=>"12/12", 2=>"12/19", 3=>"12/26", 4...

答案 2 :(得分:0)

在Ruby中,通常有很多方法可以编写任何非平凡的构造。这是另一个:

range = 1.week.ago.to_date..Date.today
array = range.each_with_index.map {|date, i| [i.to_s, date.strftime('%m/%d')]}.flatten
Hash[*array]