liveBook · Manning

Conditional logic

As explained in The Well-Grounded Rubyist, Fourth Edition

if is a Ruby conditional construct that executes code when a condition is truthy and can provide alternative branches.

Suppose a ticket has an `available?` method. An `if` can print a success message when the method’s result is truthy and a sold-out message otherwise. Conditional logic changes which code runs according to the value of an expression. section 2.2.4 section 6.0

The basic form is `if condition`, followed by code and a closing `end`. Add `else` for an alternative. Add any number of `elsif` clauses to test further conditions: Ruby runs the first successful branch and skips the rest. A final `else` runs only if every test fails. Branches can contain more code or nested conditionals. section 6.1.1

def print_conditionally
  print "Enter an integer: "
  n = gets.to_i
  if n > 0
    puts "Your number is positive."
  elsif n < 0 
    puts "Your number is negative."
  else
    puts "Your number is zero."
  end
end
print_conditionally

Try entering a positive integer, a negative integer, and zero. The same `if`/`elsif`/`else` statement selects a different message for each. section 6.1.1

A condition need not produce the object `true`. Ruby tests the truthiness of its result: only `false` and `nil` fail an `if` test. Strings, numbers, and even `0` pass. This distinction matters when a method has a side effect: `puts` prints its argument but returns `nil`, so `if puts "hello"` prints `hello` without entering the branch. section 2.2.4 section 7.5.1

Choose the form that keeps the decision clear:

  • Use `unless` for a negative test, or negate an `if` test with `not` or `!`. Parenthesize a comparison after `!` when you mean to negate the whole comparison; operator precedence can otherwise change the test. section 6.1.1
  • Use a trailing modifier for a short guard, as in `puts "Big number!" if x > 100`. A multiline `if` is easier to follow when there are several branches. section 6.1.1

An `if` is also an expression. If no condition succeeds and there is no `else`, its value is `nil`. In irb, distinguish a message printed by a branch from the value irb reports for the entire expression: a branch calling `puts` also yields `nil` because `puts` returns `nil`. section 2.2.4 section 6.1.1

if false
  x = 1
end
p x      #1
p y      #2

The condition is false, so `x = 1` never runs. Ruby nevertheless recognizes `x` as a local variable while parsing; inspecting it yields `nil`, while inspecting the undeclared `y` raises an error. section 6.1.2

Assigning a match while testing it

`if m = /la/.match(name)` both assigns the match result and tests it. The successful branch can use `m.pre_match` and `m.post_match`; the `else` branch handles no match. Be careful not to confuse assignment (`=`) with comparison (`==`) in a condition. section 6.1.2 section 1.1.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Works through branching, truthiness, expression values, negation, and parse-time assignment behavior.
Examples
Uses keyboard-entered integers to select three branches and a regular-expression match to guard match-data access.
What it assumes
Builds on method calls, comparisons, and local variables while showing basic conditional syntax directly.
What you can do after
Practice/perform Ruby branching with `if`, `elsif`, `else`, `unless`, and truthy expression results.
How it connects
Connects to Boolean values, method return values, local variables, operator precedence, and regular-expression matching.

Also explained in

Compare how 21 books explain conditional logic →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.