Flip-Flop operator

suggest change

The flip flop operator .. is used between two conditions in a conditional statement:

(1..5).select do |e|
  e if (e == 2) .. (e == 4)
end
# => [2, 3, 4]

The condition is false until the first part is true. It then stays true through the element that makes the second part true, and is false again after that.

This example illustrates what is being selected:

[1, 2, 2, 3, 4, 4, 5].select do |e|
  e if (e == 2) .. (e == 4)
end
# => [2, 2, 3, 4]

The flip-flop works only in if, unless, and the ternary operator. Anywhere else, .. is the range operator.

(1..5).select do |e|
  (e == 2) .. (e == 4)
end
# => ArgumentError: bad value for range

It can switch from false to true and backwards multiple times:

((1..5).to_a * 2).select do |e|
  e if (e == 2) .. (e == 4)
end
# => [2, 3, 4, 2, 3, 4]

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents