NormalizeCountry

Convert country names and codes to a standard.

Overview

require "normalize_country"

NormalizeCountry("America")                       # "United States"
NormalizeCountry("United States of America")      # "United States"
NormalizeCountry("USA",  :to => :official)        # "United States of America"
NormalizeCountry("Iran", :to => :official)        # "Islamic Republic of Iran"
NormalizeCountry("U.S.", :to => :alpha2)          # "US"
NormalizeCountry("US",   :to => :fifa)            # "USA"
NormalizeCountry("Iran", :to => :alpha3)          # "IRN"
NormalizeCountry("Iran", :to => :ioc)             # "IRI"
NormalizeCountry("DPRK", :to => :short)           # "North Korea"
NormalizeCountry("North Korea", :to => :iso_name) # "Korea, Democratic People's Republic Of"

# Or
NormalizeCountry.convert("U.S.", :to => :alpha2)  # "US"

# Set the default
NormalizeCountry.to = :alpha3 
NormalizeCountry.convert("Mexico")                 # "MEX"
NormalizeCountry.convert("United Mexican States")  # "MEX"

Supported Conversions

In addition to trying to convert from common, non-standardized names and abbrivations, NormalizeCountry will convert to/from the following:

:alpha2

ISO 3166-1 alpha-2

:alpha3

ISO 3166-1 alpha-3

:fifa

FIFA (International Federation of Association Football)

:official

The country's official name

:ioc

International Olympic Committee

:iso_name

Country name used by ISO 3166-1

:short

A shortned version of the country's name, commonly used when speaking and/or writing (US English)

Faulty/Missing/Erroneous Country Names

Please submit a patch or open an issue.

Why?

This code was -to some extent- part of a larger project that allowed users to perform a free-text search by country. Country names were stored in the DB by their ISO names.

Several years later at work we had to extract country names from a web service that didn't standardize them. Sometimes they used UK, other times U.K. It then occured to me that this code could be useful outside of the original project. The web service was fixed but, nevertheless…

Somewhat Similar Gems

Upon further investigation I've found the following:

  • Carmen: ISO country names and states/subdivisions

  • countries ISO country names, states/subdivisions, currency, E.164 phone numbers and language translations

  • country_codes ISO country names and currency data

  • i18n_data: ISO country names in different languages, includes alpha codes

  • ModelUN: Similar to this gem but with less support for conversion, it does include US states