我有不同的包含单位的散列,分组为单位类型。我的代码旨在确定应返回哪种单元类型以进行进一步处理。但是,当检查每个列表时,会出现很多重复。第一个 if 与第一个 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