Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,227 questions

56,129 answers

573 users

How to get the country name from the 2-letter country code (alpha-2) in Ruby

2 Answers

0 votes
# ------------------------------------------------------------
# Static lookup table; extend as needed.
# Defined at the top level so it's a proper constant.
# ------------------------------------------------------------
COUNTRY_MAP = {
  "CA" => "Canada",
  "CN" => "China",
  "DE" => "Germany",
  "FR" => "France",
  "GB" => "United Kingdom",
  "SK" => "South Korea",
  "IN" => "India",
  "JP" => "Japan",
  "US" => "United States"
}.freeze

# ------------------------------------------------------------
# get_country_name
# Receives a 2‑letter ISO country code and returns the
# corresponding country name.
#
# Uses a Hash for O(1) lookups.
# Input is normalized to uppercase to ensure consistent matching.
# Returns nil if the code is not found.
# ------------------------------------------------------------
def get_country_name(alpha2)
  # Normalize input
  code = alpha2.strip.upcase

  # Lookup
  COUNTRY_MAP[code]
end

# ------------------------------------------------------------
# main
# Demonstrates the lookup function with several sample codes.
# ------------------------------------------------------------
def main
  codes = ["US", "GB", "FR", "JP", "ZZ"] # ZZ is intentionally invalid

  codes.each do |code|
    name = get_country_name(code)

    if name
      puts "#{code} → #{name}"
    else
      puts "#{code} → (invalid code)"
    end
  end
end

main


=begin
run:

US → United States
GB → United Kingdom
FR → France
JP → Japan
ZZ → (invalid code)

=end

 



answered 1 day ago by avibootz
0 votes
COUNTRY_NAMES = {
  'US' => 'United States',
  'CA' => 'Canada',
  'GB' => 'United Kingdom',
  'FR' => 'France',
  'DE' => 'Germany',
  'JP' => 'Japan'
  # Add codes as needed
}.freeze

def country_name_for(code)
  COUNTRY_NAMES[code.to_s.upcase] || 'Unknown Country'
end

puts country_name_for('jp') # => "Japan"



# run:
#
# Japan
#

 



answered 1 day ago by avibootz
...