Kamil Łęczycki
Kamil Łęczycki

Reputation: 189

Ruby get arrays of dates based on given period

I have question is there maybe a fine simple solution to this task:

I have first_date = "2011-02-02" , last_date = "2013-01-20" and period = 90 (days).

I need to get arrays with two elements for example:
[first_date, first_date + period] ... [some_date, last_date].

I will make it with some kind of a loop but maybe there is some nice fancy way to do this :D.

Upvotes: 0

Views: 296

Answers (2)

steenslag
steenslag

Reputation: 80065

Date has a step method:

require 'date'
first_date = Date.parse("2011-02-02")
last_date = Date.parse("2013-02-20")
period = 90

p first_date.step(last_date-period, period).map{|d| [d, d+period]}
#or
p first_date.step(last_date, period).map.each_cons(2).to_a

Upvotes: 1

Arnaud Meuret
Arnaud Meuret

Reputation: 984

require 'pp'
require 'date'

first_date=Date.parse "2011-02-02"
last_date=Date.parse "2013-01-20"
period = 90
periods = []

current = first_date
last = current + period

while(last < last_date ) do
  periods << [current, last]
  current = last  
  last = current + period
end

if periods[-1][1] != last_date  
  periods << [periods[-1][1], last_date]
end

p periods

I am assuming that the last period must end on last_date regardless of its length, as your question implies.

Upvotes: 0

Related Questions