Ruby 返回两个日期时间之间每小时的数组
我希望输出的Ruby 返回两个日期时间之间每小时的数组,ruby,Ruby,我希望输出的date\u glob如下所示: {2015-{07-{19-{21,22,23},20-{00,01,02,03,04,05,06,07,08,09,10}}}} 我感谢你的帮助。下面是我的脚本 require 'date' date_glob = ""; y = 0; m = 0; (DateTime.new(2015,7,19,21,0,0)..DateTime.new(2015,7,20,10,0,0)).each do |d| if d.year != y
date\u glob
如下所示:
{2015-{07-{19-{21,22,23},20-{00,01,02,03,04,05,06,07,08,09,10}}}}
我感谢你的帮助。下面是我的脚本
require 'date'
date_glob = ""; y = 0; m = 0;
(DateTime.new(2015,7,19,21,0,0)..DateTime.new(2015,7,20,10,0,0)).each do |d|
if d.year != y
date_glob = "#{date_glob.chomp(',')}}}," if y != 0
date_glob+= "#{d.year}-{"
m = 0
end
if d.month != m
date_glob = "#{date_glob.chomp(',')}}," if m != 0
date_glob+= sprintf("%02d-{",d.month)
end
date_glob+= sprintf("%02d-",d.day)
date_glob+= sprintf("%02d,",d.hour)
y = d.year
m = d.month
end
date_glob = "{#{date_glob.chomp(',')}}}}"
一个简单的解决方案可以是:
date = DateTime.new(2015,7,19,21,0,0)
end_date = DateTime.new(2015,7,20,10,0,0)
hash = {}
while date <= end_date
hash[date.year] ||= {}
hash[date.year][date.month] ||= {}
hash[date.year][date.month][date.day] ||= []
hash[date.year][date.month][date.day] << date.hour
date = date.in(1.hour)
end
hash
=> {2015=>{7=>{19=>[21, 22, 23], 20=>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}}}
hash.to_s.gsub("=>",'-').gsub("[","{").gsub("]","}").gsub(/\s+/,'')
=> "{2015-{7-{19-{21,22,23},20-{0,1,2,3,4,5,6,7,8,9,10}}}}"
date=DateTime.new(2015,7,19,21,0,0)
结束日期=日期时间。新(2015,7,20,10,0,0)
哈希={}
而日期{7=>{19=>[21,22,23],20=>[0,1,2,3,4,5,6,7,8,9,10]}
hash.to_.gsub(“=>”,“-”).gsub(“[”,“{”).gsub(“],“}”).gsub(/\s+/,”)
=> "{2015-{7-{19-{21,22,23},20-{0,1,2,3,4,5,6,7,8,9,10}}}}"
{2015-{07-{19-{21,22,23},20-{00,01,02,03,04,05,06,07,08,09,10}}}
应该是字符串吗?如果是这样,你需要用引号括起来。