1

I want to return a hash key/value pair based on max key value. I know max_by works, but it stops at the first result. How can I return all results in the event of a tie?

{
  foo: 1,
  bar: 3,
  baz: 3
}.max_by { |key, value| value }

#=> [:bar 3] # Only bar comes back, but baz also has a value of 3.

1 Answer 1

1

I'd do :

hash = {
         foo: 1,
         bar: 3,
         baz: 3
       }

hash.group_by { |_,value| value }.max_by { |key,_| key }.last
# => [[:bar, 3], [:baz, 3]]

Breaking of the above code :

hash.group_by { |_,v| v } 
# => {1=>[[:foo, 1]], 3=>[[:bar, 3], [:baz, 3]]}
hash.group_by { |_,v| v }.max_by { |k,_| k }
# => [3, [[:bar, 3], [:baz, 3]]]
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. What's the _ meant to be? Is it the key? Why not use key?
+1! Thank you. I was not aware of the _. Is it documented any where?
@JumbalayaWanton Yes it is.. But I need to search.. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.