Reputation: 839
if country == "Switzerland"
icon_link = "ch"
elsif country == "Poland"
icon_link = "pl"
elsif country == "Germany"
icon_link = "de"
elsif country == "Spain"
icon_link = "sp"
elsif country == "Japan"
icon_link = "jp"
elsif country == "Kazakhstan"
icon_link = "kz"
elsif country == "Hong Kong"
icon_link = "hk"
elsif country == "China"
icon_link = "cn"
end
image_tag("icons/flags/#{icon_link}.png",options)
I'm guessing I would need to create an array and use the keys but don't figure out how to do it.
Thanks for your help.
Upvotes: 0
Views: 134
Reputation: 27845
For your special need, I would recommend the Hash-solution in the other answers.
As an alternative you may use case instead the if-elsif-construct.
case country
when "Switzerland"
icon_link = "ch"
when "Poland"
icon_link = "pl"
when "Germany"
icon_link = "de"
when "Spain"
icon_link = "sp"
when "Japan"
icon_link = "jp"
when "Kazakhstan"
icon_link = "kz"
when "Hong Kong"
icon_link = "hk"
when "China"
icon_link = "cn"
end
You can integrate case also as paramter:
image_tag("icons/flags/%s.png" % case country
when "Switzerland"
"ch"
when "Poland"
"pl"
when "Germany"
"de"
when "Spain"
"sp"
when "Japan"
"jp"
when "Kazakhstan"
"kz"
when "Hong Kong"
"hk"
when "China"
"cn"
else
"dummy"
end, options)
Upvotes: 1
Reputation: 33954
In Ruby, a Hash can do this. In other languages, similar functionality is sometimes called an "associative array". Basically they take a key (in your case the country) and a value (the locale code, such as 'cn').
Declare the hash:
country_codes = {"Switzerland" => "ch", "Poland" => "pl", etc.... }
/ key \ / value \ / key \ /value\
With the hash declared above:
country_codes["Switzerland"] => "ch"
Then you use it like:
image_tag("icons/flags/#{country_codes[country]}.png",options)
See: http://www.troubleshooters.com/codecorn/ruby/basictutorial.htm#_Hashes
Upvotes: 1
Reputation: 1959
You likely want a Hash:
# do this part once to load your hash
countryCode = {
"Switzerland" => "ch",
"Germany" => "de",
# ...
}
# generate the image_tag call
if( countryCode.has_key?( country ) )
image_tag( "icons/flags/#{countryCode[country]}.png",options)
else
# country code not in your hash
end
Upvotes: 4
Reputation: 2967
icon_links = { "Switzerland" => "ch",
"Poland"=> "pl",
"Germany" => "de",
"Spain" => "sp",
"Japan" => "jp",
"Kazakhstan" => "kz",
"Hong Kong" => "hk",
"China" => "cn"}
icon_link = icon_links[country]
image_tag("icons/flags/#{icon_link}.png",options)
Upvotes: 1