11

I have the following array:

[["2010-01-10", 2], ["2010-01-09", 5], ["2009-12-11", 3], ["2009-12-12", 12], ["2009-12-13", 0]]

I just want to sort it by the second value in each group and return the highest one, like i want to the output to be 12 with the given input above.

update

I might add that I made this into an array using to_a, from a hash, so if there is away to do the same with a hash that would be even better.

4 Answers 4

31

To sort by second value

x=[["2010-01-10", 2], ["2010-01-09", 5], ["2009-12-11", 3], ["2009-12-12", 12], ["2009-12-13", 0]]

x.sort_by{|k|k[1]}
=> [["2009-12-13", 0], ["2010-01-10", 2], ["2009-12-11", 3], ["2010-01-09", 5], ["2009-12-12", 12]]
Sign up to request clarification or add additional context in comments.

1 Comment

just to note: sort_by requires Ruby 1.8.7+
8

Use this on your hash:

hash.values.max

If you only need the highest element, there is no need to sort it!

1 Comment

I'm almost embarrassed for asking the question now. Thanks +1
8

Call the sort method on your hash to sort it.

hash = hash.sort { |a, b| b[1] <=> a[1] }

Then convert your hash to an array and extract the first value.

result = hash.to_a[0][1]

Comments

3

If you want the key-value pair with the max value:

hash.max_by {|key, val| val} # => ["2009-12-12", 12]

requires Ruby 1.8.7+

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.