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
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.
A shorter version of kranzky answer:
data.map(&:value).max
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With