How do I get the highest value in a Ruby hash?

0

I have this hash,

meses_ventas = {'Enero' => 2000, 'Febrero' => 3000, 'Marzo' => 1000, 'Abril' => 5000, 'Mayo' => 4000}

And I need to get the highest value among all the values. It turns out that I try to iterate it with each, but I can not get the highest value of the hash that means 5000 of the month of April to be stored in a variable.

    
asked by Upset Grade 03.05.2018 в 04:52
source

2 answers

1

If you only need to get the highest value of the hash ( 5000 ), the best thing you can do is to work directly with the values instead of the key-value pairs.

meses_ventas.values.max
# => 5000

values returns an Array with all values, and as in your case all values or pairs are numbers ( Integer ), you can use the max method that returns the object with max imo value.

Important to note that the max method would return an error ( ArgumentError ) if you had Integer s and String s combined in the values.

Greetings.

    
answered by 03.05.2018 / 07:52
source
1

You can use max_by that will return an array similar to this: [llave, par] . Then it calls only the last element of the array.

meses_ventas.max_by{ |llave, par| par }[-1]
# => 5000

You can 'read' it in the following way:

The hash meses_ventas applies max_by with the arguments llave and par , and then returns the one with the par greater. We only call par , but since it is max_by , we know that it will be the par higher.

Finally, what returns is an Array, where the first object is llave and the last one is par . The [-1] is responsible for returning the last element of the array ['Abril', 5000] , that is, 5000 .

    
answered by 03.05.2018 в 06:14