2012-12-09 182 views
1

我有不同的散列包含單位,分組爲單位類型。我的代碼旨在確定哪些單位類型應該返回進行進一步處理。但是,每個列表都經過檢查後會出現大量重複。第一個與第一個elsif完全相同。我如何以最好的方式幹代碼?刪除通過陣列時的重複

from_unit = "gr" 
to_unit = "kg" 

WEIGHT = { 
"gr" => 1000.0, 
"kg" => 1.0, 
} 

MEASURE = { 
"mm" => 1000.0, 
"cm" => 100.0, 
"m" => 1.0 
} 

if WEIGHT.has_key?(from_unit) or WEIGHT.has_key?(to_unit) 
    if WEIGHT.has_key?(from_unit) && WEIGHT.has_key?(to_unit) 
    return WEIGHT 
    elsif WEIGHT.has_key?(from_unit) 
    raise RuntimeError, "#{to_unit} is not a known unit" 
    else 
    raise RuntimeError, "#{from_unit} is not a known unit" 
    end 
elsif MEASURE.has_key?(from_unit) or MEASURE.has_key?(to_unit) 
    if MEASURE.has_key?(from_unit) && MEASURE.has_key?(to_unit) 
    return WEIGHT 
    elsif MEASURE.has_key?(from_unit) 
    raise RuntimeError, "#{to_unit} is not a known unit" 
    else 
    raise RuntimeError, "#{from_unit} is not a known unit" 
    end 
else 
    raise RuntimeError, "You can't convert #{from_unit} into #{to_unit}" 
end 
+2

參考http://codereview.stackexchange.com/ – Jan

+0

你可以使用'||''&&'或'和''或'(布爾表達式的習慣用法是第一種),但不要混合它們!另外,不要寫一個明確的'return',那也不是慣用的。 – tokland

回答

6

去,這片段確實少檢查比你(真的有必要嗎?),但能夠完成任務:

def get_table(from_unit, to_unit) 
    [WEIGHT, MEASURE].detect do |table| 
    table[from_unit] && table[to_unit] 
    end or fail("You can't convert #{from_unit} into #{to_unit}") 
end 
+0

輝煌。謝謝。 – ChristofferJoergensen

1

你可以做這樣的事情:爲了簡單

if !MEASURE.has_key?(from_unit) and !WEIGHT.has_key?(from_unit) 
    raise RuntimeError, "#{from_unit} is not a known unit" 

if !MEASURE.has_key?(to_unit) and !WEIGHT.has_key?(to_unit) 
    raise RuntimeError, "#{to_unit} is not a known unit" 

if WEIGHT.has_key?(from_unit) and WEIGHT.has_key?(to_unit) 
    return WEIGHT 

if MEASURE.has_key?(from_unit) and MEASURE.has_key?(to_unit) 
    return MEASURE # Was this a typo? 

raise RuntimeError, "You can't convert #{from_unit} into #{to_unit}" 
+0

你是對的,這是一個錯字:-) – ChristofferJoergensen