使用 delta 迭代 Ruby Time 对象 [英] Iterate over Ruby Time object with delta

查看:40
本文介绍了使用 delta 迭代 Ruby Time 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Ruby 中迭代时间范围并设置增量?

Is there a way to iterate over a Time range in Ruby, and set the delta?

这是我想做的事情的一个想法:

Here is an idea of what I would like to do:

for hour in (start_time..end_time, hour)
    hour #=> Time object set to hour
end

您可以遍历 Time 对象,但它会在两者之间每秒返回一次.我真正需要的是一种设置偏移量或增量(例如分钟、小时等)的方法

You can iterate over the Time objects, but it returns every second between the two. What I really need is a way to set the offset or delta (such as minute, hour, etc.)

这是 Ruby 内置的,还是有不错的插件可用?

Is this built in to Ruby, or is there a decent plugin available?

推荐答案

在 1.9 之前,您可以使用 Range#step:

Prior to 1.9, you could use Range#step:

(start_time..end_time).step(3600) do |hour|
  # ...
end

然而,这个策略很慢,因为它会调用 Time#succ 3600 次.反而,正如 dolzenko 在 他的回答 中指出的那样,更有效的解决方案是使用简单的循环:

However, this strategy is quite slow since it would call Time#succ 3600 times. Instead, as pointed out by dolzenko in his answer, a more efficient solution is to use a simple loop:

hour = start_time
while hour < end_time
  # ...
  hour += 3600
end

如果您使用 Rails,您可以将 3600 替换为 1.hour,这样可读性更强.

If you're using Rails you can replace 3600 with 1.hour, which is significantly more readable.

这篇关于使用 delta 迭代 Ruby Time 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆