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
source to share
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.
source to share