I am working on a problem I found on the internet:
The human body goes through 90 minute sleep cycles during the night, and you feel more refreshed if you wake up at the end of a sleep cycle than if you wake up during a sleep cycle. The challenge is to make a program that takes a wake-up time and outputs the possible times to fall asleep so that you will wake up at the end of a sleep cycle.*
My approach to this problem is to subtract 90m from the time five times after parsing it to DateTime and storing it into an array. However, I’m new to Rails and am not quite sure how to do this. How do I display my time in the original format?
Here is what I have so far:
require 'date'
def sleep_time time
a = []
5.times do |i|
multiple = i * 90 * 60
a << time - multiple
end
puts a
end
puts "Enter wake-up time: "
time = DateTime.strptime(gets, '%I:%M %p').to_time
puts time
sleep_time(time)
Edit: I figured out how to subtract 90m (using seconds).
Time supports
strftime, which takes a format string that is consistent withstrptime. Use:For instance:
Also, don’t parse it into a DateTime object then convert to a Time object using
to_time. Instead parse directly into a Time object. Time supportsstrptimealso:If you want to parse from a given format, then output in that format again, define a constant and use it in the
strptimeandstrftimemethods: