You can’t handle the Truthy

Arun M
Rube’s Guide
Published in
3 min readJul 23, 2017

The concept of “truthy” and “falsey” is programming jargon. These terms refer to the Boolean states — True and False. Understanding how a programming language (like Ruby) interprets a true or false statement will help you write better code.

Put simply, a falsey statement is one where the result of that line of code will be either false or nil. A truthy statement refers to every other possible result.

Consider this line of code:

if amihungry == true
puts "Time to eat"
end

We are trying to determine if line 1 is truthy or falsey. If it is truthy, line 2 will be output. If it is falsey, the loop ends. Since amihungry is set to equal “true”, the statement is true and the output will be “Time to Eat”.

There is a shorthand that can applied to this example:

if amihungry
puts "Time to eat"
end

The == true part is an assumed portion of the code and does not need to be expressed. Often times, this will not be written in code and it is important to understand why that is.

amihungry = nil
if amihungry
puts "Time to eat"
end

This is an example of a falsey statement. We have determined that the variable is nil. Therefore when the if statement makes the call to amihungry, it receives nil which we know is falsey. The loop ends there.

&& vs ||

&& is the AND operator. || is the OR operator. When reading a && expression, Ruby will move forward as long as the first object before the && is truthy. When reading a || expression, Ruby will move forward only if the first object is falsey.

Let’s use an example to illustrate this. What is the output for the following expressions?

(5 || 6) && (“WAT” || 9)nil && (true || true || true)

The first thing that should be pointed out here is the parentheses in the expressions. Order of operations is used here similar to mathematics.

In the first example, the output will be “WAT”. Why is this? (5 || 6) will choose 5 because 5 is not falsey. (“WAT” || 9) will choose “WAT” for the same reason. Now, the expression has become the much simpler to parse5 && “WAT”. The resulting output will be “WAT”

In the second example, we look first at the contents of the parentheses. true || true || true becomes simply true because on the first comparison of true || true, the condition is not falsey so Ruby stops right there and accepts true. The resulting expression becomes nil && true. The output here is of course nil because the first object does not satisfy the main requirement of the && operator which is that it must be truthy.

The logic can get tricky. It may be a good idea to brush up on your OOP from math class.

--

--