From: Robert Klemme Date: 2010-09-09T15:25:09+09:00 Subject: Re: Key Associated w/ Maximum Value in Hash On 09.09.2010 05:23, Josh Cheek wrote: > On Wed, Sep 8, 2010 at 9:57 PM, Timothy Baronwrote: > >> Simple question: what's the cleanest way to retrieve a key associated >> with the maximum value of a hash. For instance, how do I retrieve 'b' >> from the following example: >> >> hash = Hash.new >> hash['a']=4 >> hash['b']=10 >> hash['c']=7 >> -- >> Posted via http://www.ruby-forum.com/. >> >> > How about Enumerable#max > > hash = {'a'=>4,'b'=>10,'c'=>7} > max_record = hash.max { |a,b| a.last<=> b.last } # => ["b", 10] > max_index = max_record&& max_record.first # => "b" In 1.9.x you can even spare the #last: irb(main):001:0> hash = {'a'=>4,'b'=>10,'c'=>7} => {"a"=>4, "b"=>10, "c"=>7} irb(main):002:0> hash.max {|(k1,v1),(k2,v2)| v1 <=> v2} => ["b", 10] Here's a version with #inject irb(main):004:0> hash.inject([nil,0]) {|(maxk,maxv),(k,v)| v > maxv ? [k,v] : [maxk,maxv]}.last => 10 Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/