Ruby 通过阵列时消除重复
我有不同的包含单位的散列,分组为单位类型。我的代码旨在确定应该返回哪个单元类型以进行进一步处理。然而,在检查每一份清单时,都会有大量重复。第一个if的操作与第一个elsif完全相同。如何以最好的方式使代码变干Ruby 通过阵列时消除重复,ruby,hash,Ruby,Hash,我有不同的包含单位的散列,分组为单位类型。我的代码旨在确定应该返回哪个单元类型以进行进一步处理。然而,在检查每一份清单时,都会有大量重复。第一个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
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
你可以这样做:
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}"
你可以这样做:
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}"
为了简单起见,此代码段比您的代码段进行的检查要少(真的有必要吗?),但可以完成以下工作:
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
为了简单起见,此代码段比您的代码段进行的检查要少(真的有必要吗?),但可以完成以下工作:
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
Cf.您可以使用
|
&&
或和或
(布尔表达式的惯用用法是第一个),但不要将它们混合使用!另外,不要编写一个显式的返回
,它也不是惯用的。Cf。您可以使用|
&&
或和
或
(布尔表达式的惯用用法是第一个),但不要混用它们!另外,不要编写一个显式的返回
,它也不是惯用的。