\$\begingroup\$
\$\endgroup\$
1
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?!
-
\$\begingroup\$ Use distance_of_time_in_words(Time.now, Time.now.end_of_day) \$\endgroup\$Victor Hazbun Anuff– Victor Hazbun Anuff2013年06月27日 18:34:28 +00:00Commented Jun 27, 2013 at 18:34
1 Answer 1
\$\begingroup\$
\$\endgroup\$
0
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
lang-rb