不少人在寫邏輯判段式時,會誤以為 && 和 || 與 and / or 是等價的,因此產出不少 bug。其實 and 和 or 跟 if / else 是等價的。所以請千萬不要在 boolean 邏輯內使用 and / or。
- 被判斷為 foo = ( 42 && foo ) / 2
foo = 42 && foo / 2
=> NoMethodError: undefined method '/' for nil:NilClassfood = 42 and foo / 2
=> 21next if widget = widgets.pop 相當於
widget = widgets.pop and next raise "Not ready!" unless ready_to_rock? 相當於
ready_to_rock? or raise "Not ready!" - Avdi 的 Using “and” and “or” in Ruby