我有不同的哈希包含单位,分组为单位类型。我的代码旨在确定应返回哪个单元类型以进行进一步处理。但是,在检查每个列表时会发生很多重复。第一个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
答案 0 :(得分: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
答案 1 :(得分: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}"