Today I Learned

hashrocket A Hashrocket project

Ruby XOR operator

The ^ acts is a boolean XOR operator in Ruby when the arguments are boolean. It wants only one true value in an expression in order to be considered true:

true ^ false ^ false
# => true

true ^ false ^ true
# => false

Let's look at 5 trues:

true ^ true ^ true ^ true ^ true 
# => true

How is this true? Each ^ is evaluated one at a time. Since true ^ true is not exclusive, it is false. So after the first evaluation, we have:

false ^ true ^ true ^ true

# false ^ true is true

true ^ true ^ true

#true and true is false
false ^ true
# true

Using this same logic we can see why true ^ true ^ true ^ true is false.

See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.