From: Hee-Sob Park Date: 2000-12-20T14:40:03+09:00 Subject: [ruby-talk:7740] Re: Code sample for improvement "Dan Schmidt" wrote in message news:wksnnkayr4.fsf@turangalila.harmonixmusic.com... > Stephen White writes: > > > I don't think closures and coroutines are going to be all that helpful > here. Here's a translation that shows some of the power of Ruby, > though it's optimized mostly for cuteness: > > def format (hash, name) > size = hash[name] > if size > 0 > "#{size} #{name}" + (size > 1 ? "s" : "") > end > end > > time = ARGV[0].to_i > > Unit = Struct.new ("Unit", :name, :div) > > units = [['year', 10000], > ['month', 12], > ['day', 30], > ['hour', 24], > ['min', 60], > ['sec', 60]].map { |u| Unit.new (*u) } > > t = {} > units.reverse.each { |u| (time, t[u.name]) = time.divmod(u.div)} > res = units.map { |u| format (t, u.name) } .join (' ').squeeze(' ').strip > > puts res > Here's my optimized version time = ARGV[0].to_i u = [60,60,24,30,12] sg = ["year","month","day","hour","min","sec"] pl = ["years","months","days","hours","mins","secs"] t = [time] u.each { |v| t[0,0] = t.shift.divmod(v) } res = "" t.each_with_index { |v,i| res += " #{v} #{v>1?pl[i]:sg[i]}" if v>0} puts res Park, Hee-Sob.