Iterate over Ruby Time object with delta

前端 未结 3 2092
攒了一身酷
攒了一身酷 2020-12-01 14:06

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         


        
3条回答
  •  独厮守ぢ
    2020-12-01 14:34

    If your start_time and end_time are actually instances of Time class then the solution with using the Range#step would be extremely inefficient since it would iterate over every second in this range with Time#succ. If you convert your times to integers the simple addition will be used but this way you will end up with something like:

    (start_time.to_i..end_time.to_i).step(3600) do |hour|
      hour = Time.at(hour)     
      # ...
    end
    

    But this also can be done with simpler and more efficient (i.e. without all the type conversions) loop:

    hour = start_time
    begin
      # ...      
    end while (hour += 3600) < end_time
    

提交回复
热议问题