Skip to content

Instantly share code, notes, and snippets.

@allolex
Created November 23, 2015 19:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save allolex/5a18331a1da7c717ff27 to your computer and use it in GitHub Desktop.
Save allolex/5a18331a1da7c717ff27 to your computer and use it in GitHub Desktop.

Inverse sorting of a hash by value

  • Explain the Hash[] syntax.
  • Demonstrate #sort_by.
  • Show how sorting hashes is not necessarily straightforward.

Let's create a hash and experiment with it.

h = { a: 10, b: 9, c: 8 }
# => {:a=>10, :b=>9, :c=>8}

Let's sort our hash.

h.sort
# => [[:a, 10], [:b, 9], [:c, 8]]

Sorting seems to convert a hash into an AoA.

We can sort by the value using #sort_by.

h.sort_by { |k, v| v }
# => [[:c, 8], [:b, 9], [:a, 10]]

Now let's reverse the order.

h.sort_by { |k, v| v }.reverse
# => [[:a, 10], [:b, 9], [:c, 8]]

If we chain #reverse onto the result, we get what we need.

Now it's time to convert it all back into a hash.

Hash[h.sort_by { |k, v| v }.reverse]
# => {:a=>10, :b=>9, :c=>8}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment