Q:

Ruby on Rails get interval values between start_at and end_at

I have question about processing time in increments in my Rails app.
I have a Schedule model with these columns:
:user_id => 1,
:day => “Sunday”,
:start_at => “08:00AM”,
:end_at => “03:30PM”,
:average_time => “30” # this average time in minutes 

I need to loop from the start_at to the end_at in 30-minute increments, like so:
08:00 AM

08:30 AM

09:00 AM

09:30 AM

10:00 AM

…

…

03:30 PM

How can I process the difference between times incrementally like this?

A:

You can use the step for a range loop to do that.  Here's an example for your model:
total_minutes = (schedule.end_at - schedule.start_at) / 60

(0..total_minutes).step(30) do |minutes|
  time = schedule.start_at + minutes*60
  puts "#{time.strftime('%H:%M')}"
end

This starts by calculating total_minutes from the difference between the start_at and end_at times, converting seconds to minutes.  This assumes that these are Ruby Time objects and not Strings; strings would need to be converted to Time before using this code.
Next, the loop progresses from the start_at in increments of 30 minutes by adding the minutes for each loop iteration (* 60) to start_at.  At each interval, the loop prints the time, until it reaches or exceeds end_at.

