2014-01-21 32 views
1

我不確定我是否試圖在此代碼中抽象得太多,或者我嘗試做的事情有一個更簡單的方法。下面是代碼:在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 

有沒有更好的方法來做到這一點?

+0

現在'if if index.even?'看起來比'if(index%2 == 0)'更好嗎? –

+0

確實是合成糖!我喜歡你的建議 – tawheed

回答

2

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 
+0

看起來不錯+1 - 這不會工作嗎?:'foo1? open_foo1,close_foo1:open_foo2,close_foo2' – fyz

+0

@feed_me_code,會導致'SyntaxError'。它有不同的語義。 – falsetru