Iterate over Ruby Time object with delta

前端 未结 3 2102
攒了一身酷
攒了一身酷 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:39

    Range#step method is very slow in this case. Use begin..end while, as dolzenko posted here.

    You can define a new method:

      def time_iterate(start_time, end_time, step, &block)
        begin
          yield(start_time)
        end while (start_time += step) <= end_time
      end
    

    then,

    start_time = Time.parse("2010/1/1")
    end_time = Time.parse("2010/1/31")
    time_iterate(start_time, end_time, 1.hour) do |t|
      puts t
    end
    

    if in rails.

提交回复
热议问题