概要
iso_country_codes gem で ISO 国名コードの国名とコードを取得します
ISO 国名コードとは?
以下を参照
国名コード - Wikipedia
インストール
$ gem install iso_country_codes
サンプル
サンプルコード
require 'pp'
require 'iso_country_codes'
def show_details(country)
puts <<-EOS
# {country.name}
#{country.numeric}
#{country.alpha2}
#{country.alpha3}
#{country.calling}
#{country.continent}
#{country.currency}
#{country.currencies}
EOS
end
# 日本, パレスチナの ISO 国名コードを取得
[392, 275].each do |code|
country = IsoCountryCodes.find(code)
show_details(country)
end
# エラー発生時はブロックに処理を記述できる
begin
IsoCountryCodes.find(999)
rescue => e
puts e.message
end
# ISO コードの昇順で ISO 国名コードの全情報を 5 件取得
pp IsoCountryCodes.all.sort_by { |e|e.numeric }.take(5)
# ISO コードの昇順で ISO 国名コード国名とコードを 5 件取得
pp IsoCountryCodes.for_select(:numeric).sort_by { |e|e.last }.take(5)
- 動作確認
Japan
392
JP
JPN
+81
AS
JPY
["JPY"]
Palestine, State of
275
PS
PSE
+970
AS
JOD
["JOD", "NIS"]
No ISO 3166-1 code could be found for '999'.
[#<IsoCountryCodes::Code::AFG:0x000006004c30c8>,
#<IsoCountryCodes::Code::ALB:0x000006004c29c0>,
#<IsoCountryCodes::Code::ATA:0x000006004c0c60>,
#<IsoCountryCodes::Code::DZA:0x000006004c2498>,
#<IsoCountryCodes::Code::ASM:0x000006004c1e08>]
[["Afghanistan", "004"],
["Albania", "008"],
["Antarctica", "010"],
["Algeria", "012"],
["American Samoa", "016"]]
コードリーディング
Singleton
singleton モジュールを利用しています。