如何从一个范围返回一系列日期和小时?

时间:2012-07-27 01:50:00

标签: ruby ruby-on-rails-3

如何从一个范围返回一系列天数和小时数?到目前为止,我已经尝试过:

(48.hours.ago..Time.now.utc).map { |time| { :hour => time.hour } }.uniq

返回:

[{:hour=>1}, {:hour=>2}, {:hour=>3}, {:hour=>4}, {:hour=>5}, {:hour=>6}, {:hour=>7}, {:hour=>8}, {:hour=>9}, {:hour=>10}, {:hour=>11}, {:hour=>12}, {:hour=>13}, {:hour=>14}, {:hour=>15}, {:hour=>16}, {:hour=>17}, {:hour=>18}, {:hour=>19}, {:hour=>20}, {:hour=>21}, {:hour=>22}, {:hour=>23}, {:hour=>0}] 

不理想,因为它每秒都会迭代一次。这需要很长时间。我收到几条警告信息:

/Users/Chris/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.2.2/lib/active_support/time_with_zone.rb:328: warning: Time#succ is obsolete; use time + 1

我正在尝试返回类似的内容:

[{:day => 25, :hour=>1}, {:day => 25, :hour=>2}, {:day => 25, :hour=>3}, {:day => 25, :hour=>4} ... {:day => 26, :hour=>1}, {:day => 26, :hour=>2}, {:day => 26, :hour=>3}, {:day => 26, :hour=>4}] 

2 个答案:

答案 0 :(得分:7)

使用Range#step,但作为预防措施,请先将日期转换为整数(显然是ranges using integers have step() optimized - YMMV)。作为一种风格问题,我也首先截断到小时。

这是一些快速的'n'脏代码:

#!/usr/bin/env ruby

require 'active_support/all'

s=48.hours.ago
n=Time.now

st=Time.local(s.year, s.month, s.day, s.hour).to_i
en=Time.local(n.year, n.month, n.day, n.hour).to_i

result = (st..en).step(1.hour).map do |i|
  t = Time.at(i)
  { day: t.day, hour: t.hour }
end

puts result.inspect

收率:

[{:day=>25, :hour=>11}, {:day=>25, :hour=>12}, {:day=>25, :hour=>13}, 
{:day=>25, :hour=>14}, {:day=>25, :hour=>15}, {:day=>25, :hour=>16},
...

答案 1 :(得分:2)

stime = 48.hours.ago
etime=Time.now.utc
h = []
while stime <= etime
  h.push({ :day => stime.day, :hour => stime.hour })
  stime += 1.hour
end