1
\$\begingroup\$

I have the following code that gets the difference in time between now and when an alarm is supposed to go off (i.e. "alarm goes off in 23 minutes, 56 seconds").

def time_to_alarm_in_words
 #AN EMPTY STRING WE WILL BE ADDING TO
 time_in_words = ''
 #THE TIME TO THE ALARM IN SECONDS
 total_seconds = (time - Time.now).to_i
 #SOME BASIC TIME UNIT VARIABLES
 days = total_seconds / 86400
 hours = (total_seconds / 3600) - (days * 24)
 minutes = (total_seconds / 60) - (hours * 60) - (days * 1440)
 seconds = total_seconds % 60
 #ONLY PROCEED IF THE TIME TO THE ALARM IS POSITIVE(I.E. IN THE FUTURE)
 unless total_seconds <= 0
 #BUILD A HASH WITH THE TIME UNTIL THE ALARM
 time_hash = {"days" => (total_seconds / 86400), 
 "hours" => ((total_seconds / 3600) - (days * 24)), 
 "minutes" => ((total_seconds / 60) - (hours * 60) - (days * 1440)),
 "seconds" => (total_seconds % 60)}
 #IF THE TIME SEGMENT IS POSITIVE, ADD IT TO THE STRING
 time_hash.each_pair do |time_segment,length|
 if value > 0
 #i.e. add "22 hours," to the empty string
 time_in_words << "#{length} #{time_segment},"
 end
 end
 #CHOP OFF THE TRAILING ','
 time_in_words.chop!
 #RETURN THE RESULT
 return time_in_words + " ago"
end 

I have a feeling I could cut this down by half. Any suggestions?!

asked Jan 27, 2012 at 22:28
\$\endgroup\$
1

1 Answer 1

1
\$\begingroup\$

Courtesy of the clever helper method from this link: https://stackoverflow.com/questions/4136248/how-to-generate-a-human-readable-time-range-using-ruby-on-rails

def humanize secs
 [[60, :seconds], [60, :minutes], [24, :hours], [1000, :days]].map{ |count, name|
 if secs > 0
 secs, n = secs.divmod(count)
 "#{n.to_i} #{name}"
 end
 }.compact.reverse.join(' ')
end
def time_to_alarm_in_words time
 #AN EMPTY STRING WE WILL BE ADDING TO
 time_in_words = ''
 #THE TIME TO THE ALARM IN SECONDS
 total_seconds = (time - Time.now).to_i
 time_in_words = humanize total_seconds
 #RETURN THE RESULT
 return time_in_words + " in the future"
end
answered Jan 27, 2012 at 22:44
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.