【问题标题】:Ruby each Iterator - Substitute the hash to iterate through based on if condition?Ruby each Iterator - 根据 if 条件替换散列以迭代?
【发布时间】:2018-05-06 11:16:44
【问题描述】:

我有两个哈希值,需要根据 if 条件的结果遍历其中一个。以下是我的代码目前的样子:

if SOME CONDITION
  hash_a.each do |x|
    some code in here
  end
else 
  hash_b.each do |x|
    the same code in here
  end

每个元素执行大约 30 行代码,所以我的问题是:有没有办法让代码看起来更像这样:

SOME CONDITION ? hash_a.each do |x| : hash_b.each do |x|
  some code in here 
end

或者以任何其他方式简化/减少它?

提前致谢!

【问题讨论】:

  • 我建议你创建一个以哈希为参数的方法。例如,def doit(hash); some code here; end。然后执行doit(condition ? hash_a : hash_b)。这可以阐明您在做什么并促进测试。

标签: ruby if-statement foreach ternary-operator


【解决方案1】:

您可以使用三元运算符直接选择要调用each的对象,例如:

(SOME_CONDITION ? hash_a : hash_b).each do |x|
  # some code in here
end

如果SOME_CONDITION 相当简单,那么这是一个不错且干净的方法。如果条件比较复杂,你应该把条件或者整个对象选择分别提取到他们自己的方法中。

【讨论】:

    猜你喜欢
    • 2019-07-08
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-30
    • 2021-08-15
    • 2010-09-06
    • 2011-08-15
    相关资源
    最近更新 更多