1

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

2 回答 2

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
于 2012-12-09T14:27:35.050 回答
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}"
于 2012-12-09T13:57:49.313 回答