Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 18 / 68

Logical Operators (AND, OR, NOT)

In this lesson you will get comfortable with Ruby's logical operators so you can combine several conditions in one decision. This is for anyone searching for "Ruby logical operators how to use".

When you want to combine conditions you use logical operators. && means "both are true", || means "at least one is true", and ! means "the opposite". They are indispensable for tests such as "18 or over and holding a ticket".

The sample code checks "18 or over and holding a ticket" with age >= 18 && has_ticket, and "under 18, or not holding a ticket" with age < 18 || !has_ticket.

A common stumbling block for beginners is mixing up && and ||. Saying the condition out loud in plain English first - "both" or "either" - before turning it into code makes mistakes far less likely.

Short-circuit evaluation is worth knowing too: if the left side of && is false, the right side is never evaluated. These operators are combined constantly in real validation code.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)