Thuta Learning
Ruby
IntermediateProgrammingBeginner

If / Else / Elsif

RubyLesson 1130 min

What you'll walk away with

  • Write if / elsif / else chains in an order that works, and spell elsif correctly
  • Use unless, statement modifiers and the ternary operator where they read better
  • Explain truthiness: only nil and false are falsy, while 0, "" and [] are truthy
  • Use if as an expression that returns a value, and avoid the = versus == trap

Explain it simply

Explain it simply

A program that always does the same thing is not very useful, so every language lets you choose between paths. In Ruby, you describe a path with if, give alternatives with elsif and else, and close the whole thing with end. It works like a row of gates: Ruby tests the first condition, and if it is true it walks through that gate and skips the others.

A condition can be any expression, and Ruby only cares whether the result counts as true or false. That rule is simpler than in many languages: only two values, nil and false, count as false. Everything else, including 0 and the empty string, counts as true.

Problem → Why → Solution

The problem: a mistyped elseif fails quietly

The most common beginner typo in Ruby branching is writing elseif, the spelling used in PHP and other languages. Ruby does not reject it. It reads elseif age < 65 as an ordinary method call placed inside the first branch, and what happens next depends on the data: for some inputs the program gives a wrong answer without any error, and for others it crashes.

The code below shows both outcomes. For age 30 the first condition is false, so Ruby jumps to else and prints senior, which is wrong. For age 10 it prints minor and then fails on the elseif line.

describe.rb
def describe(age)
  if age < 18
    puts "minor"
  elseif age < 65      # not a keyword: Ruby reads this as a method call
    puts "adult"
  else
    puts "senior"
  end
end

describe(30)           # prints "senior": wrong, and no error at all
describe(10)           # prints "minor", then NoMethodError: undefined method 'elseif'

Why is the typo so quiet?

In Ruby, elsif is the only keyword for a second condition. elseif is just an unknown word, and an unknown word followed by an argument is parsed as a call to a method with that name. Ruby only discovers that the method does not exist when it actually runs that line, which is why the failure depends on the input. Spelling it elsif, with no e between the l and the s, fixes it, and a quick test of every branch would have caught it.

Core concept: the first truthy branch runs, and only that one

An if statement has up to three parts: if with a condition, any number of elsif branches, and an optional else, closed by end. There are no parentheses around the condition and no braces around the branches. Ruby tests the conditions from top to bottom and runs the first branch whose condition is truthy; the rest are skipped, so the order of the branches matters.

Ruby decides truthiness with one rule: nil and false are falsy, and every other value is truthy. That includes 0, the empty string, an empty array and an empty hash, which are falsy in several other languages. So if count is true even when count is 0. To test for emptiness, ask the object itself: count.zero?, text.empty?, list.empty? or value.nil?. The table summarizes the surprises.

ValueInside an ifAsk this instead
0truthyzero?
"" (empty string)truthyempty?
[] and {}truthyempty?
nilfalsynil?
falsefalsy(it is already false)

if is an expression, so it has a value: the value of the last line in the branch that ran, or nil if no branch ran. That lets you write label = if age >= 18 then "adult" else "minor" end. Ruby also offers shorter forms for simple cases: a statement modifier (puts "free" if total > 100), unless for the negative (puts "sorry" unless in_stock), and the ternary operator (condition ? a : b), which should stay on one line and never be nested.

For numeric tests the comparison operators (<, <=, >, >=, ==, !=) cover most cases, and between?(18, 64) or (18..64).cover?(age) states a range in a single expression. A comparison returns true or false, which is exactly what an if wants. Remember too that && and || stop as soon as the answer is known, so in total.nil? || total.negative? the negative? call never happens when total is nil.

Mental model: a row of gates
  1. Test the first condition
  2. Truthy: run that branch, skip the rest
  3. Falsy: move on to the next elsif
  4. else catches whatever is left

Ruby tries the gates from top to bottom and walks through the first one that opens; else is the last gate in the row.

General pattern

ruby
if condition_a
  # runs when condition_a is truthy
elsif condition_b
  # runs when condition_b is truthy
else
  # runs when nothing above matched
end

result = condition ? value_if_truthy : value_if_falsy
do_something if condition        # modifier form
do_something unless condition    # runs when condition is falsy

elsif and else are optional, and the statement always closes with end. The last three lines are the short forms: the ternary picks a value, and the two modifiers guard a single statement with a condition.

Example: sorting ages into three bands

A person's age falls into one of three bands: under 18, 18 to 64, or 65 and over. Ruby checks the branches in order, so the example prints exactly one of three messages. With age = 20 the first test fails, the second passes, and the else branch is skipped.

Change age to 10 and then to 70 and run it again to see the other two branches. Predicting the result before you run it is the best way to practise how a branch gets chosen.

ruby
age = 20

if age < 18
  puts "You are a minor."
elsif age >= 18 && age < 65
  puts "You are an adult."
else
  puts "You are a senior."
end

Code breakdown

  1. The inputage = 20

    A local variable holding the value to test. Change it to 10 or 70 and run again to see the other two branches.

  2. First testif age < 18

    The first condition. age < 18 is false for 20, so Ruby skips this branch and moves on to the next test.

  3. Second testelsif age >= 18 && age < 65

    The second condition uses && so both comparisons must be true. The first half is redundant: by the time Ruby reaches elsif, age < 18 has already failed, so elsif age < 65 would behave the same.

  4. Catch-allelse

    The catch-all branch has no condition and runs only when every test above was falsy, here for ages 65 and over.

  5. The resultputs "You are an adult."

    Only the branch that ran prints, so the program shows exactly one line. Every other puts line was skipped.

You should see
You are an adult.

Truthiness in practice

The best way to check the truthiness rule is to ask if about a range of values. The code below uses the ?: ternary to print whether each value is truthy or falsy, and ljust(8) lines up the columns.

truthiness.rb
values = [0, "", [], {}, "false", nil, false]

values.each do |value|
  state = value ? "truthy" : "falsy"
  puts "#{value.inspect.ljust(8)} is #{state}"
end

In the output, 0, "", [], {} and "false" are all truthy, and only nil and false are falsy. Notice that the string "false" is truthy because it contains characters, which is why a "false" that arrives from a form cannot be tested with a plain if; you have to compare it with == "false".

if as an expression, unless, modifiers and the ternary

The result of an if can be stored straight into a variable. The code below shows four forms: a one-line if...then...else, a modifier after puts, a ternary, and ||=, which means assign only when the value is nil. The last part shows that an if whose branch never ran gives nil.

forms.rb
stock = 0
price = 12

label = if stock.zero? then "sold out" else "in stock" end
puts label
puts "free shipping" if price > 10
puts "add more items" unless price > 10
discount = price > 10 ? 0.1 : 0
puts discount

nickname = nil
nickname ||= "guest"
puts nickname

shipping = if price > 50
             0
           end
p shipping

The output is sold out, free shipping, 0.1, guest and nil. "add more items" is not printed because price > 10 is true, so unless skips it. For shipping, price > 50 is false, no branch runs, and the if gives nil. Avoid combining unless with else; rewriting it as an if is clearer.

Combining conditions: && and the and/or trap

To combine conditions, use && (both), || (either) and ! (not). Ruby also has the words and, or and not, but their precedence is very low. ok = true and false is split as (ok = true) and false, so ok is assigned true first and the and is applied afterwards, which surprises quite a few people.

operators.rb
logged_in = true
banned = false

puts "welcome" if logged_in && !banned

ok = true and false
p ok
ok = (true and false)
p ok
ok = true && false
p ok

The output is welcome, true, false and false. The first ok is true because of the precedence of and; with && the result is false. Do not mix up = and ==, either: if n = 10 assigns 10 to n and then tests the assigned value, which is always truthy, and because the right side is a literal, Ruby 4.0.9 warns with found '= literal' in conditional, should be ==.

In real projects

Where this shows up in real projects

Branching is how programs enforce rules: showing a discount only to members, rejecting a form whose email is blank, sending a different email when a payment fails. In Rails controllers you will see guard clauses such as return unless user.active?, which end the method early so the main path stays flat instead of being buried under nested ifs.

Because if returns a value, Ruby code often assigns the result of a branch directly, as in status = if paid? then "paid" else "pending" end, or ends a method with a small if/else that is the method's return value. Teams usually reserve the ternary for tiny choices and switch to if/elsif or a case statement when there are three or more outcomes, so each branch stays easy to read and to test.

Common mistakes

Common mistakes

1. Writing elseif or else if

elseif is not a keyword, so it is read as a method call and gives a wrong answer or a NoMethodError. else if (two words) is allowed, but it starts a second, nested if that needs its own end. Write elsif.

2. Using = instead of ==

if n = 10 assigns 10 to n, and the condition is always truthy, so the branch always runs and the old value of n is lost. When the right side is a literal, as here, Ruby prints a warning (found '= literal' in conditional, should be ==) but does not stop the program, so read warnings. To compare, write if n == 10.

3. Assuming 0 or an empty string is false

puts "no items" if count always prints, even when count is 0, because 0 is truthy. Write puts "no items" if count.zero?, and use empty? for strings and arrays.

4. Putting the broader test first

With score = 95, if score >= 60 ... elsif score >= 90 prints only pass and never reaches honors, because 95 already satisfied the first condition. Put the narrowest, most specific test first, or test every branch with several values.

Best practices

Best practices

  • Use guard clauses (return unless ...) to avoid deep nesting, and keep the main path flush left.
  • Phrase conditions positively; use unless only for one simple negative condition, and never add an else to it.
  • Use the ternary for one short choice and never nest it.
  • Ask the object (zero?, empty?, nil?) instead of relying on truthiness for 0 and "".

Mini challenge

Mini challenge: a shipping-fee label

Write a method shipping_label(total, member: false) that returns the shipping label for an order. Combine a guard clause, if/elsif/else and a keyword argument.

  • Return "invalid order" first when total is nil or negative (a guard clause)
  • Return "free (member)" for members
  • Return "free" for 100 or more, "5.00" for 50 or more, and "10.00" for everything else
  • The method returns a string; do the printing outside the method
shipping.rb
def shipping_label(total, member: false)
  # TODO: guard: "invalid order" when total is nil or negative
  # TODO: members ship free: "free (member)"
  # TODO: 100 or more is "free", 50 or more is "5.00", anything else is "10.00"
end

# TODO: print the label for nil, 30 as a member, 120, 60 and 20

Expected: invalid order free (member) free 5.00 10.00

Show hint

Check nil first: nil.negative? would raise NoMethodError, so write total.nil? || total.negative? in that order, because || stops as soon as the left side is true. Write the rest as if/elsif/else, with the narrower 100 test before 50.

Show solution
shipping.rb
def shipping_label(total, member: false)
  return "invalid order" if total.nil? || total.negative?

  if member
    "free (member)"
  elsif total >= 100
    "free"
  elsif total >= 50
    "5.00"
  else
    "10.00"
  end
end

puts shipping_label(nil)
puts shipping_label(30, member: true)
puts shipping_label(120)
puts shipping_label(60)
puts shipping_label(20)

Quick quiz 1 / 3

With list = [], what happens with puts "empty" if list?

Quick quiz 2 / 3

With score = 95, what prints for if score >= 60 then puts "pass" and elsif score >= 90 then puts "honors"?

Quick quiz 3 / 3

What happens with if n = 10, with a single equals sign?

What to remember

  • if / elsif / else tests conditions from top to bottom and runs only the first truthy branch; elsif is the correct spelling.
  • Only nil and false are falsy; 0, "", [] and {} are truthy, so ask with zero?, empty? or nil?.
  • if is an expression that returns a value, and modifiers, unless and the ternary are shorter forms for simple cases.
  • Use &&, || and ! in conditions, and watch out for the low precedence of and/or and for = versus ==.

Official Ruby Documentation — Ruby Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

If / Else / Elsif | Thuta Learning