views:

66

answers:

2

Hello,

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?

+3  A: 

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" }
Dancrumb
Thank you @Dancrumb
Adnan
+1  A: 

Using sort_by the whole thing becomes a bit more concise. Plus puts automatically adds the "\n":

COUNTRIES.sort_by { |k, v| v }.each { |country| puts country[0] }
Michael Kohl