0018 Flip_flop

The obscure conditional expression

The « flip-flop » is a conditional expression that hides an « ON/OFF » state. Ruby differentiates it from a Range when used in a control expression (if, while, !, …). The format is (condition turn ON) .. (condition turn OFF).

0018-flip_flop_1.png

Here’s the equivalent of the previous code without the flip-flop, so you can see how it works.

0018-flip_flop_2.png

We came across it again during an exercise involving the display of temperatures when the cooling system is in operation. This turns on when the temperature exceeds 40° and off when it drops below 30°. Easy with the « flip-flop »!

0018-flip_flop_3.png

Of course, you mustn’t overdo it… An example found on the net of the famous fizz-buzz problem with the « flip-flop » (and without the modulo operator!). You can notice an exclusive Range delaying the turn off condition to the next iteration.

0018-flip_flop_4.png

In fact, it was almost removed, starting with a warning about its use in 2.6, but finally retained because it was used by a number of us (https://bugs.ruby-lang.org/issues/5400). And what about you?

Link to Ruby documentation for flip-flop.