Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails select maximum value from array of hash

i have a array of hashes like this and i want to take the maximum value of that

data = [{name: "abc", value: "10.0"}, {name: "def", value: "15.0"}, {name: "ghi", value: "20.0"}, {name: "jkl", value: "50.0"}, {name: "mno", value: "30.0"}]

i want to select the maximum value of array of hashes, output i want is like data: "50.0"

how possible i do that, i've try this but it is seem doesnt work and just give me an error

data.select {|x| x.max['value'] }

any help will be very appreciated

like image 406
azy Avatar asked Jan 08 '15 07:01

azy


3 Answers

There are lots of ways of doing this in Ruby. Here are two. You could pass a block to Array#max as follows:

  > data.max { |a, b| a[:value] <=> b[:value] }[:value]
   => "50.0"

Or you could use Array#map to rip the :value entries out of the Hash:

  > data.map { |d| d[:value] }.max
   => "50.0"

Note that you might want to use #to_f or Float(...) to avoid doing String-String comparisons, depending on what your use case is.

like image 54
kranzky Avatar answered Sep 25 '22 12:09

kranzky


A shorter version of kranzky answer:

data.map(&:value).max
like image 42
Frank Etoundi Avatar answered Sep 23 '22 12:09

Frank Etoundi


You can also sort the array of hashes and get the values by index.

array = array.sort_by {|k| k[:value] }.reverse

puts array[0][:value]

Useful if you need minimum, second largest etc. too.

like image 37
Linju Avatar answered Sep 22 '22 12:09

Linju