Flip-flop operator
Flip-flop operator is a range operator. It is used between two conditions inside a loop. It evaluates to true when first condition is true and continues with same truth value until the second condition evaluates to true. It then starts returning false after the second condition is met until the first condition evaluates to true again.
Example:
Suppose we want to write some conditions for a 10 minutes interval training where the person should run for 45 seconds and then take a break for 15 seconds. The code for the same with flip-fop operators will be as follows.
Above code will print Run
for 45 iterations
and print Break
for next 15 iterations.
This cycle repeats until 600 seconds is reached.
The flip-flop also comes in handy for text processing.
Flip-flop operator with three dot range
There are two types of ranges in Ruby the two dot and the three dot.
The two dot range creates an inclusive range.
If we use flip-flop operator with two dot range
and conditions which are evaluating to true
in the same pass then the loop will return
false always after the first condition
is evaluated to true.
Example:
The three dot range creates a range that excludes high value.
Example:
Ruby 2.6
The usage of flip-flop operator was warned in Ruby 2.6. The reason for the deprecation was mentioned as lack of knowledge and usage of the feauture in the ticket.
Ruby 2.7
Later lot of developers came up with issues regarding removal of the operator as they were using it for text processing and scripting. So the deprecation was reverted in Ruby 2.7.