Today I Learned

hashrocket A Hashrocket project

Or Operator Precedence

What's the difference between || and or in Ruby?

Let's look at an example to find out. First, let's start with some boolean variables:

> a, b = false, true
=> [false, true]

Now, let's try the different or operators:

> a || b
=> true
> a or b
=> true

Cool, they seem to work as expected.

Finally, let's capture the result in a variable:

> c = a or b
=> true
> c
=> false

But why is c false and not true? Operator precedence. The assignment operator (=) takes precedence over the or operator causing c to be assigned to the value of a (false) before or'd with b.

source

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.