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?
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?
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)