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

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

A shorter version of kranzky answer:

data.map(&:value).max

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.