From: alex_land Date: 2007-07-12T06:05:01+09:00 Subject: Re: Beautiful Code : Pity he didn't ask here... Well i for one am feeling pretty good that i learned Ruby here and not from a textbook. Anyway, nice work. Editors are probably wishing they would have gone with "Cute Code" or "Decent-Looking Code." --alex On Jul 10, 2:15 am, John Carter wrote: > Just got the O'Reilly announcement of the book "Beautiful > Code"... here is the sample chapter by Tim Bray on Ruby! > > http://www.oreilly.com/catalog/9780596510046/chapter/ch04.pdf > > Pity he didn't run his examples by this forum first, I'm sure we could > have made them more beautiful.. > > Well, maybe for the 2nd edition, heres my bash at cleaning it up... > > For example scanning a log file..... > > EXAMPLE 4-2 . Printing article names > 1 ARGF.each_line do |line| > 2 if line =~ %r{GET /ongoing/When/\d\d\dx/(\d\d\d\d/\d\d/\d\d/[^ .]+) } > 3 puts $1 > 4 end > 5 end > > Since most Linux distro's roll the log files to a reasonable size I would have just gone with... > > ARGF.read.scan( %r{GET /ongoing/When/\d\d\dx/(\d\d\d\d/\d\d/\d\d/[^ .]+) }) do |match| > puts $1 > end > > In Example 4.3 he has... > 1 counts = {} > 2 counts.default = 0 > > Personally I prefer... > counts = Hash.new(0) > or > counts = Hash.new{|hash,key| hash[key]=0} > buts that's personal preference I guess. > > In example 4.4 he rightly identifies line 10 as a little ugly and bemoans the lack of sort_by_value in hash. > 10 keys_by_count = counts.keys.sort { |a, b| counts[b] <=> counts[a] } > it seems he doesn't know about.. > > count.keys.sort_by{|key| count[key]} > > Of course he could have done... > > class Hash > def sort_keys_by_value > keys.sort_by{|key| fetch(key)} > end > end > > Example 4.5 looks like a poster child for the Hash.new block approach... > 4 @hash = {}