我不確定我是否試圖在此代碼中抽象得太多,或者我嘗試做的事情有一個更簡單的方法。下面是代碼:在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
有沒有更好的方法來做到這一點?
現在'if if index.even?'看起來比'if(index%2 == 0)'更好嗎? –
確實是合成糖!我喜歡你的建議 – tawheed