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 evaluates to false until the first part becomes true. Then it evaluates to true until the second part becomes true. After that it switches to false again.

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 operator only works inside ifs (including unless) and ternary operator. Otherwise it is being considered as 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