- 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}