Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find lowest value in a hash

Tags:

ruby

a = { 
      1 => ["walmart", "walmart.com", 300.0], 
      2 => ["amazon", "amazon.com", 350.0], 
      ...
    } 

How do I find the element with lowest value of the float value in its array?

like image 789
chief Avatar asked Jan 01 '12 22:01

chief


2 Answers

min_by is available as a method from the Enumerable module.

It gets the array of all values in the Hash, and then picks the minimum value based on the last element of each array.

a.values.min_by(&:last)
like image 135
Anurag Avatar answered Oct 26 '22 11:10

Anurag


Another useful method is sort_by from the Enumerable module as well. It will arrange your hash from ascending order. Then chain the method with first to grab the lowest value.

a.sort_by { |key, value| value }.first
like image 40
Keenan Jade Turner Avatar answered Oct 26 '22 11:10

Keenan Jade Turner