Rails picks the maximum value from an array of hashes

I have an array of hashes like this and I want to take the maximum value of this

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 an array of hashes, the output I want is like data: "50.0"

As far as I can go, I tried this but doesn't seem to work and just gave me an error.

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

      

any help would be much appreciated

+3


source to share


3 answers


There are many ways to do this in Ruby. Here are two. You can pass a block Array#max

like this:

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

      

Or you can use Array#map

to copy records :value

from Hash

:



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

      

Note that you can use #to_f

or Float(...)

to avoid comparing String-String, depending on your usage.

+5


source


You can also sort the hash array and get the values ​​by index.

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

puts array[0][:value]

      



Useful if you want the minimum, the second largest, etc. also.

0


source


A shorter version of kranzky :

data.map(&:value).max

      

0


source







All Articles