考虑一组日期时间:
2010-07-17 16:09:00 -0700
2010-07-17 16:10:00 -0700
2010-07-17 16:12:00 -0700
2010-07-17 17:44:00 -0700
2010-07-18 02:12:00 -0700
迭代数组并插入缺少的分钟是什么样的干净且惯用的方法,以便输出为:
2010-07-17 16:09:00 -0700
2010-07-17 16:10:00 -0700
2012-07-17 16:11:00 -0700
2010-07-17 16:12:00 -0700
2010-07-17 16:13:00 -0700
...
Ruby 1.9.3
编辑:更多信息:
它实际上是一个哈希数组,以日期时间为关键:
2010-07-17 16:09:00 -0700 => 5
2010-07-17 16:10:00 -0700 => 22
2010-07-17 16:12:00 -0700 => 3
因此,每个缺失的分钟都应该具有前一分钟的值。
此外,不使用Rails。
答案 0 :(得分:1)
require 'date'
# dummy dates
dates = "2010-07-17 16:09:00 -0700
2010-07-17 16:10:00 -0700
2010-07-17 16:12:00 -0700
2010-07-17 17:44:00 -0700
2010-07-18 02:12:00 -0700"
datetimes = dates.lines.map{|s| DateTime.parse(s) }
continuous_datetimes = [datetimes.min]
while continuous_datetimes.last < datetimes.max
continuous_datetimes.push( continuous_datetimes.last + 1.0/24.0/60.0 )
end
continuous_datetimes.first(10).each{|d| puts d}
# 2010-07-17T16:09:00-07:00
# 2010-07-17T16:10:00-07:00
# 2010-07-17T16:11:00-07:00
# 2010-07-17T16:12:00-07:00
# 2010-07-17T16:13:00-07:00
# 2010-07-17T16:14:00-07:00
# 2010-07-17T16:15:00-07:00
# 2010-07-17T16:16:00-07:00
# 2010-07-17T16:17:00-07:00
# 2010-07-17T16:18:00-07:00
以下代码反映了您的哈希结构。
设定:
require 'date'
# dummy dates
hash = {
DateTime.parse("2010-07-17 16:09:00 -0700") => 5,
DateTime.parse("2010-07-17 16:10:00 -0700") => 22,
DateTime.parse("2010-07-17 16:12:00 -0700") => 3
}
实际代码:
new_hash = hash.inject(Hash[ *hash.first ]) do |tmp,kv|
while tmp.keys.last < kv.first
tmp[ tmp.keys.last + 1.0/24.0/60.0 ] = kv.last
end
tmp
end
输出:
new_hash.each {|k,v| puts "#{k} => #{v}" }
# 2010-07-17T16:09:00-07:00 => 5
# 2010-07-17T16:10:00-07:00 => 22
# 2010-07-17T16:11:00-07:00 => 3
# 2010-07-17T16:12:00-07:00 => 3