Limited Offer
60% OFF on all plans!

Conditionals in Ruby

Control program flow using if, elsif, else, unless, ternary expressions, and case/when statements in Ruby.

Introduction to Conditionals

Conditionals let your program make decisions. Ruby evaluates any value as a condition — only `nil` and `false` are falsy; everything else (including `0` and `""`) is truthy.

1. What Are Conditionals?

A conditional runs a block of code only when a condition is met.

if / elsif / else

Ruby's `if` statement supports multiple branches with `elsif` and a fallback with `else`.

1. if / else

Run one block if the condition is true, another if it is false.

2. if / elsif / else

Add as many `elsif` branches as needed between `if` and `else`.

3. Inline if (Modifier Form)

Place `if` at the end of a statement for a concise one-liner.

Truthy & Falsy Values

In Ruby, only `nil` and `false` are falsy. Every other value — including `0`, `""`, and `[]` — is truthy.

1. The Only Falsy Values

Ruby has exactly two falsy values: `false` and `nil`.

2. Checking for nil

Use `nil?` for explicit nil checks rather than relying on truthiness.

Logical Conditions

Combine conditions with `&&` (AND), `||` (OR), and `!` (NOT) to build compound checks.

1. AND (&&) and OR (||)

`&&` requires both sides to be true; `||` requires at least one.

2. NOT (!)

`!` negates a boolean; `!=` checks inequality.

unless — The Ruby "if not"

`unless` is Ruby's way of writing "if not". It reads more naturally for negative conditions.

1. unless Statement

`unless condition` runs the block when the condition is false.

2. Inline unless

Place `unless` at the end of a statement for a clean one-liner.

case / when Statement

Ruby's `case/when` is more powerful than a traditional switch. Each `when` uses `===`, so you can match values, ranges, classes, and regexes.

1. Basic case / when

Match a value against several possible cases.

2. case with Ranges

Match against ranges for numeric classification.

3. case with Types (Class Matching)

Match based on the class of the value using `is_a?` semantics.

4. case with Regex

Match strings against regular expression patterns.

Nested & Ladder if-else

Nested `if` statements handle multiple independent conditions. Ladder `elsif` chains handle mutually exclusive conditions.

1. Nested if

Put an `if` inside another `if` when conditions are independent.

Guard Clauses

Guard clauses use `return` at the top of a method to handle edge cases early, keeping the happy path flat.

1. Guard Clause Pattern

Return early for invalid inputs instead of wrapping the whole method in an `if`.

Best Practices

Follow these guidelines to keep your conditionals simple, readable, and maintainable.

1. Prefer Positive Conditions

Positive conditions are easier to read than double negatives.

2. Use case over Long elsif Chains

When comparing one variable to many values, `case` is cleaner than a chain of `elsif`.