I recently submitted a code-challenge for an interview according to the following guidelines:
About
Write a function or method that accepts two mandatory arguments and returns a result.
Requirements:
- Use Ruby or another language of your choosing, and write production quality code.
- Your function or method should not use any date/time library.
- The first argument is a time value in the form of a string with the following format:
[H]H:MM {AM|PM}
- The second argument is the number of minutes, as an integer value
- The return value of the function should be a string of the same format as the first
argument, which is a result of adding the minutes to the time.
- For example,
add_minutes('9:13 AM', 10)
would return9:23 AM
- For example,
Additional notes:
- We just want to see how you code, so this exercise is not meant to be too hard or take too long.
- If you spend an hour on this, stop coding and finalize by adding some notes about what you would do if you had more time.
Although my Ruby proficiency has somewhat atrophied due to primarily working with php for the last 8 months, I was able to produce the following well-within one-hour of beginning the challenge:
# FIRST ATTEMPT
# require 'time'
# def flux_capacitor(time,mins)
# the_time = Time.parse(time.to_s)
# mins = the_time + 10*60
# end
# FINAL REFACTOR
def flux_capacitor(time,mins)
the_time = time.scan(/\d/).join('').to_i
meridian = time.scan(/(A|M|P)/).join('')
new_time = the_time + mins
back_in_time = new_time.to_s.insert(-3,':') + " #{meridian}"
end
puts flux_capacitor("9:13 AM",10)
puts flux_capacitor("9:13 PM",10)
p flux_capacitor("10:13 PM",10).class
# DOX
# http://ruby-doc.org/core-2.2.3/Time.html
# https://www.ruby-forum.com/topic/125709
# https://www.ruby-forum.com/topic/104359
# http://apidock.com/ruby/String/insert
# http://rubular.com/
Simply-stated, is there a better approach? I've asked others and they think my solution is fairly clean. Obviously, I know my solution could benefit with a conditional statement for edge cases (e.g. flux_capacitor("9:50 AM", 15)
).