From: dblack@... Date: 2007-07-10T21:12:09+09:00 Subject: Re: Beautiful Code : Pity he didn't ask here... Hi -- On Tue, 10 Jul 2007, John Carter wrote: > 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. Yes, but be careful: your two lines don't do the same thing as each other: irb(main):007:0> counts = Hash.new(0) => {} irb(main):008:0> counts["hi"] => 0 irb(main):009:0> counts => {} irb(main):010:0> counts = Hash.new{|hash,key| hash[key]=0} => {} irb(main):011:0> counts["hi"] => 0 irb(main):012:0> counts => {"hi"=>0} > 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 It's best not to get into changing the core language, though, if the book isn't going to discuss the benefits and pitfalls of doing so in depth. David -- * Books: RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242) RUBY FOR RAILS (http://www.manning.com/black) * Ruby/Rails training & consulting: Ruby Power and Light, LLC (http://www.rubypal.com)