From: daz Date: 2005-07-06T18:15:46+09:00 Subject: Re: (newb) converting seconds into plain english time units luke wrote: > hi, > > [...] at the moment it's making everything a plural! > > > def format_time seconds > hours = (seconds / (60 * 60)) > plural = "s" if hours.to_i > 1 > time = "#{hours.to_i} hour#{plural}" > if hours > 23 > days = hours / 24 > plural = "s" if days.to_i > 1 > time = "#{days.to_i} day#{plural}" > if days > 30 > weeks = days / 7 > plural = "s" if weeks.to_i > 1 > time = "#{weeks.to_i} week#{plural}" > end > end > > time > end > > [...] > > any help would be much appreciated. > The reason you're getting plural is that "plural" is only set to 's', never ''. Here's one way which is probably similar to the way Robert was describing. (Haven't checked it rigorously ;) #---------------------------------------------------- def format_time(seconds) arr = [ ['second', [3600] ], ['hour', [24] ], ['day', [31, 7] ], ['week', nil ], ] t = seconds aix = 0 while (lim = arr[aix][1]) ## ternary operator cond ? true : false (t >= lim[0]) ? t /= lim[-1] : break aix += 1 end ## % is a method of the String class (like sprintf) '%4d %s%s' % [t, arr[aix][0], (t == 1) ? '' : 's'] end [ 0, #-> 0 seconds 1, #-> 1 second 36, #-> 36 seconds 3599, #-> 3599 seconds 3600, #-> 1 hour 3601, #-> 1 hour 3600*4, #-> 4 hours 3600*23, #-> 23 hours 3600*24*2, #-> 2 days 3600*24*7, #-> 7 days 3600*24*30, #-> 30 days 3600*24*31, #-> 4 weeks 3600*24*32, #-> 4 weeks 3600*24*60, #-> 8 weeks 3600*24*100, #-> 14 weeks ].each do |secs| puts format_time(secs) end #---------------------------------------------------- daz