Skip to the workspace
Pebellslearn by building
Operators  ›  Lesson

Logical Operators

Logical 12 min&& stops at the first falsy value and || stops at the first truthy one, each returning the value it stopped on, while and, or and not bind more loosely than assignment.

ruby / Logical Operators

Explore each scene at your own pace.

01 · The rule

The rule

Logical Operators

&& stops at the first falsy value and || stops at the first truthy one, each returning the value it stopped on, while and, or and not bind more loosely than assignment.

Trace short-circuit results and account for operator precedence.

Bean Cart offers a discount when the customer has a loyalty card and the order is at least 5.00, or when it is the last hour before closing. Joining conditions like that is the job of the logical operators, and Ruby's versions have a useful twist: they return one of the actual values, not only true or false.

The rule

&& stops at the first falsy, || stops at the first truthy.

The three symbols:

  • && reads as "and": true when both sides are truthy.
  • || reads as "or": true when at least one side is truthy.
  • ! reads as "not": true when the value is falsy.
has_card = true
total = 6.0
last_hour = false

has_card && total >= 5      # => true
last_hour || total > 10     # => false
!last_hour                  # => true

Both && and || short-circuit: they evaluate from left to right and stop as soon as the answer is known. And the result is the last value they looked at, not a converted boolean:

nil || "Guest"        # => "Guest"
"Priya" || "Guest"    # => "Priya"
nil && "Guest"        # => nil
"Priya" && "Guest"    # => "Guest"

That makes || a neat way to supply a default: name = input_name || "Guest".

Short-circuiting also protects you. In order && order.size > 0, if order is nil, Ruby never calls order.size, so there is no error.

Ruby also has the words and, or and not. They look friendlier, but they bind more loosely than =, which causes surprises:

ok = true and false   # ok is true! Read as: (ok = true) and false
ok = true && false    # ok is false

Use &&, || and ! in conditions and assignments. Keep and and or for control flow, such as save or raise "failed", if you use them at all.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.