Ruby 每个迭代器 - 替换散列以根据 if 条件进行迭代?

Ruby each Iterator - Substitute the hash to iterate through based on if condition?

我有两个散列,需要根据 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

或者simplify/reduce还有其他什么方式吗?

提前致谢!

你可以直接select对象用三元运算符调用each,例如:

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

如果 SOME_CONDITION 相当简单,那么这是一个很好且干净的方法。如果条件比较复杂,你应该将条件甚至整个对象selection分别提取到他们自己的方法中。