0

I have a hash:

hash = {"key1" => [1, a], "key2" => [3, c], "key3" => [2, b]}

I need to sort the hash by the second element of the values like this:

hash = {"key1" => [1, a], "key3" => [2, b], "key2" => [3, c]}

How I can do this?

1
  • 1
    @Ursus They are ordered as of 1.9. Docs: ruby-doc.org/core-1.9.3/Hash.html "Hashes enumerate their values in the order that the corresponding keys were inserted." Commented Oct 16, 2017 at 20:20

2 Answers 2

2

Try this one

hash.sort_by { |_k, v| v.last }.to_h
Sign up to request clarification or add additional context in comments.

Comments

2

The first thing to note here is that as of Ruby 1.9, Ruby hashes are in fact ordered (docs).

To answer your question, you can use Enumerable#sort_by like so:

hash.sort_by{ |k, v| v[1] }.to_h

This sorts by the second member of each of the value arrays, and returns it as an array of pairs. Then it converts that array of pairs back into a hash (with to_h)

3 Comments

Ruby 1.9 was released about ten years ago. It's not even maintained anymore. Absolutely no need to mention new features of 1.9. If anyone is sticking to it, its their problem.
There was a comment on the question saying that hashes are not ordered. That comment has since been deleted, but that’s what I was reacting to.
It was mine, sorry :D

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.