Method: TimeCalc#iterate

Defined in:
lib/time_calc.rb

#iterate(span, unit) {|Time/Date/DateTime| ... } ⇒ Date, ...

Like #+, but allows conditional skipping of some periods. Increases value by ‘unit` at least `span` times, on each iteration checking with block provided if this point matches desired period; if it is not, it is skipped without increasing iterations counter. Useful for “business date/time” algorithms.

Examples:

# add 10 working days.
TimeCalc.(Time.parse('2019-07-03 23:28:54')).iterate(10, :days) { |t| (1..5).cover?(t.wday) }
# => 2019-07-17 23:28:54 +0300

# add 12 working hours
TimeCalc.(Time.parse('2019-07-03 13:28:54')).iterate(12, :hours) { |t| (9...18).cover?(t.hour) }
# => 2019-07-04 16:28:54 +0300

# negative spans are working, too:
TimeCalc.(Time.parse('2019-07-03 13:28:54')).iterate(-12, :hours) { |t| (9...18).cover?(t.hour) }
# => 2019-07-02 10:28:54 +0300

# zero span could be used to robustly enforce value into acceptable range
# (increasing forward till block is true):
TimeCalc.(Time.parse('2019-07-03 23:28:54')).iterate(0, :hours) { |t| (9...18).cover?(t.hour) }
# => 2019-07-04 09:28:54 +0300

Parameters:

  • span (Integer)

    Could be positive or negative

  • unit (Symbol)

Yields:

  • (Time/Date/DateTime)

    Object of wrapped class

Yield Returns:

  • (true, false)

    If this point in time is “suitable”. If the falsey value is returned, iteration is skipped without increasing the counter.

Returns:

  • (Date, Time, DateTime)

    value of the same type that was initial wrapped value.



# File 'lib/time_calc.rb', line 193