Ruby: && vs and

Richard J. Huelves
2 min readOct 21, 2019

--

gif source: http://giphygifs.s3.amazonaws.com/media/5SWGrXiPgtqZq/giphy.gif

‘&&’ or ‘and’ are interchangeable, right? The TL;DR, yes and no. Well, that answer didn’t help you much. Go ahead and take 2 minutes out of your life to see why.

Both are considered as “Logical AND” operators so they will both return true if both values are true. Ruby was meant to be a coding language that is “readable” and is often the preferred choice since it reads like plain English.

The big difference is the order of precedence. Think of it as the order of operations in math. If you had the following problem, 1 + 2 * 3, the answer would be 7, not 9. In math, we know that multiplication/division takes precedence over addition/subtraction. In Ruby, ‘&&’ takes precedence over ‘and’.

To give us a better understanding lets take a look at the precedence of Ruby operators.

table source: https://www.techotopia.com/index.php/Ruby_Operator_Precedence

As we can see from the table, the order of precedence is ‘&’, ‘=”, and ‘and’ respectively. With that in mind, let’s take a look at the following examples.

Although we’re using the same “Logical AND”, they do not provide us the same results due to their order of precedence.

gif source: https://media.giphy.com/media/3OfNDMhTCi7zW/giphy.gif

--

--