gpt4 book ai didi

ruby - 遍历数组时删除重复项

转载 作者:太空宇宙 更新时间:2023-11-03 17:17:02 25 4
gpt4 key购买 nike

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

最佳答案

为了简单起见,这个代码片段比你的检查更少(真的有必要吗?),但完成了工作:

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

关于ruby - 遍历数组时删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13788014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com