8

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

azy
  • 153
  • 1
  • 11

3 Answers3

15

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.

kranzky
  • 1,328
  • 11
  • 16
2

A shorter version of kranzky answer:

data.map(&:value).max
Frank Etoundi
  • 336
  • 3
  • 10
1

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.

Linju
  • 335
  • 3
  • 9