jackneedshelp
jackneedshelp

Reputation: 137

How to get the highest second value from an hash

I have an hash like the following.

myhash = {123=>["pizza", 9.99], 234=>["Bread", 132.0], 456=>["burgers", 5.24]}

I want to be able to somehow get it to only show the highest priced object which in this case is bread.

So the result would be same as

puts "234 Bread 132.0"

Upvotes: 0

Views: 125

Answers (2)

Ursus
Ursus

Reputation: 30056

highest_priced_object = myhash.max_by { |id, (item, price)| price }

Upvotes: 4

Eric Duminil
Eric Duminil

Reputation: 54223

Max_by accepts a block, in which you can define the value you'd like to use for comparison. In this case, the second (or last) element in the array. Finally, join concatenates everything into a String.

myhash.max_by { |_, values| values.last }.join(' ')

Upvotes: 1

Related Questions