0

Given a hash of arrays, I need to get the key for which the first element of the array is minimal.

For instance, for:

h = { :a => [8,9,1], :b => [7,2,3], :c => [1,7,3] }

I'd like to get :c as result because 1 is the min of [8,7,1]

How can I do this elegantly?

1
  • @TheTinMan : nothing really showable Commented Sep 27, 2012 at 19:29

2 Answers 2

3
h.key(h.values.min_by &:first)
Sign up to request clarification or add additional context in comments.

2 Comments

you should also let your first (longer) solution
@JCLL Find the min value don't need to sort, so i prefer min_by.
0
h.sort_by { |k,v| v[0] }[0][0]
# or (equivalent)
h.sort_by { |k,v| v.first }.first.first

By using the default array comparator, this can even be shortened to:

h.sort_by { |k,v| v }[0][0]

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.