Ruby if else语句重构

时间:2015-11-19 03:29:14

标签: ruby refactoring

目前的代码有效:

def launched_city(country, city, city_link)
  return 'current' if country == 'Malaysia' && ('Kuala Lumpur' == city_link)
  return 'current' if country == 'Philippines' && ('Manila' == city_link)
  if country == 'Australia'
    return 'current' if city == 'Melbourne' && ('Melbourne' == city_link)
    return 'current' if city == 'Sydney' && ('Sydney' == city_link)
    return 'current' if city == 'Perth' && ('Perth' == city_link)
  end
  nil
end

但我认为这很丑陋。有什么帮助吗?

我尝试使用case阻止。它失败了case语句,因为我需要检查第二个语句。我也试过了if elsif else块。在这种情况下它是一样的。

1 个答案:

答案 0 :(得分:2)

COUNTRY_LINKS = { 'Malaysia'=>['Kuala Lumpur'],
                  'Philippines'=>['Manila'],
                  'Australia'=>['Melbourne', 'Sydney', 'Perth'] }

def launched_city(country, city, city_link)
  if COUNTRY_LINKS.has_key?(country) && COUNTRY_LINKS[country].include? city_link) &&
    (country != 'Australia' || city == city_link)
    'current'
  end
end