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:
On Wed, Sep 8, 2010 at 9:57 PM, Timothy Baron <timothy.baron@gmail.com>wrote:
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:
p h.select{|x,i| i==h.values.max}.keys #> ["b", "d"]
Harry
···
On Thu, Sep 9, 2010 at 11:57 AM, Timothy Baron <timothy.baron@gmail.com> wrote:
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:
On Wed, Sep 8, 2010 at 9:57 PM, Timothy Baron<timothy.baron@gmail.com>wrote:
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:
I've tried several of these approaches, and they all work well. I'm
curious, too, about which is the fastest, but for my small hashs,
there's no noticable difference.
Adam Prescott wrote:
···
This won't capture multiple maximum values, but:
hash.invert[hash.values.max]
I'd be interested to see a benchmark profile of the suggestions.
Don't bother optimizing it for speed unless you are sure it's a bottleneck. Choose whichever option is the most readable and maintainable.
Ben
···
On Sep 9, 2010, at 23:00, Timothy Baron wrote:
I've tried several of these approaches, and they all work well. I'm
curious, too, about which is the fastest, but for my small hashs,
there's no noticable difference.
On Fri, Sep 10, 2010 at 5:20 AM, Ben Giddings <bg-rubytalk@infofiend.com>wrote:
On Sep 9, 2010, at 23:00, Timothy Baron wrote:
I've tried several of these approaches, and they all work well. I'm
curious, too, about which is the fastest, but for my small hashs,
there's no noticable difference.
Don't bother optimizing it for speed unless you are sure it's a bottleneck.
Choose whichever option is the most readable and maintainable.
I wonder why nobody used Enumerable#max_by or Hash#key (#index in 1.8):
HASH.max_by(&:last).first
HASH.key HASH.values.max
And it reveals there are both relatively efficient.
I could not help to DRY a bit the tests
Regards,
B.D.
···
On 12 September 2010 18:29, Douglas Seifert <doug@dseifert.net> wrote: