Ruby 2.7 reverts the deprecation of flip-flop operator


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.

(1..600).each do |time|
    sleep 1
    puts (time % 60 == 1)..((time-45)%60 == 0) ?  "Run" : "Break"
end
 => 1..600

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:

(1..20).each do |number|
    puts number if (number == 10)..(number == 10)
end
10
=> 1..20

The three dot range creates a range that excludes high value.

Example:

(1..20).each do |number|
    puts number if (number == 10)...(number == 10)
end
10
11
12
13
14
15
16
17
18
19
20

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.

(1..50).each do |number|
    puts number if (number == 21)..(number == 25)
end
warning: flip-flop is deprecated
21
22
23
24
25
 => 1..50

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.

(1..50).each do |number|
    puts number if (number == 21)..(number == 25)
end
21
22
23
24
25
 => 1..50