Ruby - Arrays - 这是一个聪明的方法:

时间:2011-08-13 00:22:34

标签: ruby arrays

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)

我猜我需要创建一个数组并使用这些键,但是不知道该怎么做。

感谢您的帮助。

4 个答案:

答案 0 :(得分:4)

你可能想要一个哈希:

# 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

答案 1 :(得分:1)

在Ruby中,Hash可以做到这一点。在其他语言中,类似的功能有时被称为“关联数组”。基本上他们拿一把钥匙(在你的情况下是国家)和一个价值(地区代码,如'cn')。

声明哈希:

country_codes = {"Switzerland" => "ch",      "Poland" => "pl", etc.... }
                    / key \     / value \     / key \   /value\

使用上面声明的哈希:

country_codes["Switzerland"] => "ch"

然后你就像使用它一样:

image_tag("icons/flags/#{country_codes[country]}.png",options)

请参阅:http://www.troubleshooters.com/codecorn/ruby/basictutorial.htm#_Hashes

答案 2 :(得分:1)

 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)

答案 3 :(得分:1)

为了您的特殊需要,我会在其他答案中推荐Hash-solution。

作为替代方案,您可以使用case而不是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

您也可以将案例整合为参数:

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)