From: Daniel Martin Date: 2007-07-10T21:11:50+09:00 Subject: Re: Beautiful Code : Pity he didn't ask here... John Carter writes: > Just got the O'Reilly announcement of the book "Beautiful > Code"... here is the sample chapter by Tim Bray on Ruby! > ... > > For example scanning a log file..... > > 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 As James said, I'm going to have to disagree on this, though I'd clean it up to: article_pattern = \ %r{GET /ongoing/When/\d\d\dx/(\d\d\d\d/\d\d/\d\d/[^ .]+) } ARGF.each_line do |line| line.scan(article_pattern) do |article,| puts article end end Look, no global variables! I agree with your use of Hash.new(0), but disagree that it's mere personal preference - it's much more common to use even the single argument form in the constructor than to use default=. It is odd that he seems unaware of Array.sort_by - anyone know when this was added to Ruby core? The book could be rather out of date. > Example 4.5 looks like a poster child for the Hash.new block approach... Agreed. I wonder if perhaps he's spent more time in python or some other dynamic language than Ruby. > In fact, I can't find any pretty reason to have the class BigHash at > all....looks like his Java roots are showing through. Yeah; in Java, you can't have code existing outside of a class, and I suspect that's a big part of it. > On the other hand both have the classic bug that (high + low) or > (l+u) overflows on large arrays... Actually, his code doesn't: java arrays can only have 2**31 entries (since their index is a java int), and java ints are always signed. Therefore, any overflow in the addition in java yields a negative integer, and >>> in java does right shift without sign extension. (That is, with 0s shifted in at the left). The glibc code does have that problem, but only on arrays that have more than (maximum size_t)/2 elements. -- s=%q( Daniel Martin -- martin@snowplow.org puts "s=%q(#{s})",s.to_a.last ) puts "s=%q(#{s})",s.to_a.last