Ruby: toggle a boolean inline?

I like to use this

@object.boolean = [email protected]

Boolean expressions are not 0 or 1 in Ruby, actually, 0 is not false

If n is numeric we are swapping 0 and 1...

n == 0 ? 1 : 0 # or...
1 - n          # or...
[1, 0][n]      # or maybe [1, 0][n & 1] # or...
class Integer; def oh_1; self==0 ? 1:0; end; end; p [12.oh_1, 0.oh_1, 1.oh_1] # or...
n.succ % 2     # or...
n ^= 1

If b already makes sense as a Ruby true or false conditional, it's going to be hard to beat:

!b

These examples differ in how they treat out-of-range input...


You can use XOR operator (exclusive or)

a = true
a # => true
a ^= true
a # => false
a ^= true
a # => true

Tags:

Ruby