I have different hashes containing units, grouped into unit types. My code aims to determine which unit type should be returned for further processing. However, a lot of duplication is going on when each list is examined. The first if is doing the exact same as the first elsif. How do I DRY the code up the best possible way?
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
Go for simplicity, this snippet does less checks than yours (are really that necessary?), but gets the job done: