Sort by values from hash table - Ruby

hashtable, ruby, ruby-on-rails

Solution

Hashes have no internal ordering. You can't sort a Hash in place, but you can use the Hash#sort method to generate a sorted array of keys and values.

You could combine this with an Array#each to iterate over the Hash in your desired order.

So, an example would be:

COUNTRIES = {
  'Albania' => 'AL', 
  'Austria' => 'AT',
  'Belgium' => 'BE',
  'Bulgaria' => 'BG',
  }

COUNTRIES.sort {|a,b| a[1] <=> b[1]}.each{ |country| print country[0],"\n" }

Problem

I have the following hash of countries; ``` COUNTRIES = { 'Albania' => 'AL', 'Austria' => 'AT', 'Belgium' => 'BE', 'Bulgaria' => 'BG', ..... } ``` Now when I output the hash the values are not ordered alphabetically AL, AT, BE, BG ....but rather in a nonsense order (at least for me) How can I output the hash having the values ordered alphabetically?

Original source