Programming Questions

  • Newest
  • Popular Tags
  • Ask Question
  • Coding Minutes Challenge in Ruby
    This is all the code I had to write for this "easy" challenge. Is there a simpler way to do this? Should this be moved into the "medium" category? It seems markedly different from the remaining easy challenges. I was able to do it under 15 minutes but if you need to define methods to help keep the code readable wouldn't you say it's worthy of "medium" difficulty? #returns integers for the number of minutes passed from the beginning of the day #12:00AM = 0, 12:00PM = 720, 11:59PM = 1439 def convert_to_minutes_passed(arr) str = arr.to_s #at this point we are being passed something like "12:30pm" #parse the string further -- break down into integers h, m = str.scan(/\w+/) pm = m.include?("p") #this returns true if its pm, false if its am m = m.scan(/\d\d/).to_s h = h.to_i m = m.to_i h = 0 if h == 12 pm==false ? h*60 + m : h*60 + m + 720 end #this function takes into account rotations through the 12 hour cycle def convert_to_time(str) #parse the string into two seperate times time1, time2 = str.split('-') #convert the times to the numbers of minutes passed since midnight start_time = convert_to_minutes_passed(time1) end_time = convert_to_minutes_passed(time2) #now, we must account for rotations through the 12 hour clock cycle if end_time < start_time end_time += 1440 end return start_time, end_time end def CountingMinutesI(str) start_time, end_time = convert_to_time(str) return end_time - start_time end # keep this function call here # to see how to enter arguments in Ruby scroll down CountingMinutesI(STDIN.gets)
    curriguy posted this question on 7/11/14 | ruby
    Answers
  • +
  • 1
  • -
  • It looks like it has been correctly moved to medium though there are definitely other ways of doing it, personally I think using too many methods make it harder to read not easier. An alternate way of doing it. def CountingMinutes(str) time1, time2 = str.split("-") hours1, minutes1= time1.split(':')[0].to_i, time1.split(':')[1][0..-2].to_i hours2, minutes2= time2.split(':')[0].to_i, time2.split(':')[1][0..-2].to_i #if pm add 12 hours to time hours1 = hours1 + 12 if time1.include?('p') hours2 = hours2 + 12 if time2.include?('p') total = ((hours2-hours1) *60)+(minutes2 - minutes1) #if total is negative add 24 hours if total < 0 total += 24*60 end #return total total end
    Log in to write an answer.