【发布时间】: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