J
John Carter
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 <=> 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 = {}
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 <=> 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 = {}