Add step method to Time : Time Extension « Time « Ruby






Add step method to Time


class Time
  def step(other_time, increment)
   raise ArgumentError, "step can't be 0" if increment == 0
    increasing = self < other_time
    if (increasing && increment < 0) || (!increasing && increment > 0)
      yield self
      return
    end
    d = self
    begin
      yield d
      d += increment
    end while (increasing ? d <= other_time : d >= other_time)
  end

  def upto(other_time)
    step(other_time, 1) { |x| yield x }
  end
end

the_first = Time.local(2004, 1, 1)
the_second = Time.local(2004, 1, 2)
the_first.step(the_second, 60 * 60 * 6) { |x| puts x }
the_first.upto(the_first) { |x| puts x }

 








Related examples in the same category

1.Add day ordinal suffix to Time
2.Validate a date