From: David Alan Black Date: 2000-12-20T08:51:40+09:00 Subject: [ruby-talk:7722] Re: Code sample for improvement On Wed, 20 Dec 2000, Steven Grady wrote: > # Given the number of seconds, convert to English description > > # !!! simpler table > table = [ [ 31557816, 'year' ], > [ 2629818, 'month' ], > [ 86400, 'day' ], > [ 3600, 'hour' ], > [ 60, 'min' ], > [ 1, 'sec' ] ] > Just for the collection: here's one reasonably fast one: def tfactor(time) result = "" $table.each do |secs_per, thing, plur| # using global var $table n = time / secs_per time %= secs_per if n > 0 if n > 1 thing = plur || thing + 's' end result += "#{n} #{thing} " end end result end and one reasonably cute one: def t2factor(time) result = "" $table.map do |s,t,p| n, time = time / s, time % s if n > 1 t = p || t + 's' end [n,t] end .find_all do |n,| n > 0 end .each do |n,t| result += "#{n} #{t} " end result end and one reasonably obfuscated one :-) def t3factor(e) j = "" $table.each do |x,y,z| q,e = %w/\/ %/.map {|u| e.send(u,x)} 0