What is the best way to toggle a boolean variable?

ruby

Solution

You can use XOR operator.

foo ^= true
foo = false
foo ^= true # => true
foo ^= true # => false

Problem

What is the best way to have a variable toggle between `true` and `false`? An obvious way is to initialize a variable `foo`: ``` foo = false ``` and do: ``` foo = foo.! ``` every time when I want to toggle. But this becomes verbose when the variable name is long. Is there a simpler way to do this (by using anything such as syntax sugar, original classes)? Especially, I wonder if there is a way to toggle by just giving it a single method: ``` foo.some_method ```

Original source