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

标签 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
}

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/

相关文章:

ruby - 为什么在 Ruby 中除法后负数会向下舍入?

ruby-on-rails - ActiveRecord 存在吗?与协会

java - 获取文件哈希性能/优化

perl - 在perl中更改多维哈希的第一个键

Ruby:合并包含数组的哈希

arrays - 为什么Ruby Koans习题中about_hashes.rb中的test_default_value_is_the_same_object的答案是数组?

ruby-on-rails - 默认情况下,Rails 如何污染事件记录列?

ruby - 什么!!在这个 Ruby 函数中是什么意思?

Ruby 哈希转置

multithreading - Perl MCE 将哈希数据返回给主进程