1

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?

3
  • how do you know what day it is? is the range guaranteed to a single day? Do you just need to print to the screen?
    – Anthony
    Commented May 24, 2016 at 16:18
  • I have records for each day, and this example for Sunday
    – zippax
    Commented May 24, 2016 at 16:26
  • Do the times always start and end with a whole or half hour?
    – Stefan
    Commented May 24, 2016 at 20:32

2 Answers 2

1

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.

1
  • @zippax Glad to hear that! Good luck! Commented May 24, 2016 at 22:27
1

Convert everything to seconds, parse the times and multiply your "average" by 60. Then simply do your loop from start_time to end_time incrementing by average. Convert back to time and print or do whatever you want.

In general, you need to convert everything to equals to be able to work on it. If that's seconds or minutes, all should work. Seconds makes it easy to work with time objects.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.