在ruby中重构条件逻辑

时间:2014-01-21 03:37:37

标签: ruby

我不确定我是否在尝试在此代码中抽象过多,或者有一种更简单的方法来实现我的目标。以下是代码:

some_hash = { "a" => 100, "b" => 200 } 
some_hash.each_with_index do |(key, value), index|
   if (index % 2 == 0)
      open_foo1
      open_foo2 # The order is important, that is why it has not been abstracted
   else
      open_foo2
   end
     close_foo1  # This is a bug what if foo1 was never opened, my other solution
                 # was to put it in the else clause but what if we never get there
     close_foo2
     # do something here that is applicable to both conditions
 end

所以我想出了这个,但感觉不对。

 some_hash.each_with_index do |(key, value), index|
       if (index % 2 == 0)
          open_foo1
          open_foo2 # The order is important, that is why it has not been abstracted
       else
          open_foo2
       end
       if (index % 2 == 0)
         close_foo1
       end  
       close_foo2 #In the worst case foo2 would be opened
       # do something here that is applicable to both conditions
     end

有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

在这两种情况下都会调用{p> open_foo2;您可以省略第一个else

重复谓词只能评估一次。

some_hash.each_with_index do |(key, value), index|
  foo1 = index % 2 == 0
  open_foo1 if foo1
  open_foo2
  close_foo1 if foo1
  close_foo2
end