0

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.

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Mmm, I didn't know about the step method (1.9.3 only). It would have been perfect if its semantics was to fully respect the limit argument. This also requires a last step to ensure the last range ends correctly on last_date, as requested. Very helpful nevertheless!
@KamilŁęczycki If you like this answer (even though mine came earlier and is more correct :-P), you should click the checkmark next to it. Additionally you can click on the up arrow next to all the answers you consider helpful.
0
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.

1 Comment

Since you're in a RoR context you may find nice and fancy to use the calculations module

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.