Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to toggle a boolean variable?

Tags:

ruby

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
like image 893
sawa Avatar asked Jul 27 '13 14:07

sawa


People also ask

How do you toggle variables in Javascript?

The NOT operator is used before the variable to be toggled and the result is assigned to the same variable. This will effectively toggle the boolean value.

Which is the correct way to declare a Boolean variable value to be true?

Boolean variables are variables that can have only two possible values: true, and false. To declare a Boolean variable, we use the keyword bool. To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false.

How do you toggle variables in C#?

In this lesson, I teach you the easiest way to flip or toggle a bool variable in C# for Unity. This is done by having your destination variable followed by the equals operator and the exclamation operator in front of the source variable and in this case the destination and the source should be the same variable.


1 Answers

You can use XOR operator.

foo ^= true

foo = false
foo ^= true # => true
foo ^= true # => false
like image 116
falsetru Avatar answered Oct 23 '22 05:10

falsetru