From: Robert Dober Date: 2007-07-10T19:09:09+09:00 Subject: Re: Beautiful Code : Pity he didn't ask here... On 7/10/07, John Carter wrote: > Just got the O'Reilly announcement of the book "Beautiful > 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 or tops = counts.sort_by{|*kv| kv.last}.reverse[0..9] puts tops.map{ |k,v| "#{v}: #{k}"} #each is just a primitive for Enumerables, right? > > > Example 4.5 looks like a poster child for the Hash.new block approach... > 4 @hash = {} > . > . > > 9 if @hash[s[0]] > 10 @hash[s[0]] << [ s[1], article ] > 11 else > 12 @hash[s[0]] = [ s[1], article ] > 13 end > > > Replace that with... > > 4 @hash = Hash.new{|hash,key| hash[key] = []} > > 10 @hash[s[0]] << [ s[1], article ] > > > That makes it real pretty code. Save for File.open(some_name).each_line Let the GC close the file!? It is not going to happen !! Robert -- I always knew that one day Smalltalk would replace Java. I just didn't know it would be called Ruby -- Kent Beck