我有不同的散列包含單位,分組爲單位類型。我的代碼旨在確定哪些單位類型應該返回進行進一步處理。但是,每個列表都經過檢查後會出現大量重複。第一個與第一個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
參考http://codereview.stackexchange.com/ – Jan
你可以使用'||''&&'或'和''或'(布爾表達式的習慣用法是第一種),但不要混合它們!另外,不要寫一個明確的'return',那也不是慣用的。 – tokland