Dave
Dave

Reputation: 19110

How do I find the hash value with the biggest key?

I'm using Ruby 2.4. How do I find an entry in a hash with the greatest key value? I have this hash

a = {1 => [1, 2], 2 => [3, 4, 5]}

Right now, I'm doing this

[a.keys.max, a[a.keys.max]]

but I figure there's a slicker way to pull this off.

Upvotes: 1

Views: 261

Answers (2)

Oleksandr Holubenko
Oleksandr Holubenko

Reputation: 4440

Also, #max find the largest key by default:

> a = {1 => [1, 2], 6 => [-1], 3 => [0] }
> a.max
#=> [6, [-1]]

Upvotes: 0

akuhn
akuhn

Reputation: 27793

Try this

k, v = hash.max_by { |key, value| key }

Upvotes: 1

Related Questions