Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 37 ยท Control Flow and Methods

Conditionals and case

Control program flow in Crystal with if, elsif, unless, the ternary operator, case/when with ranges and types, case/in pattern matching and truthiness rules, with Ruby stand-ins.

Programs make decisions. Crystal's conditionals look like Ruby's: if, elsif, else, unless, a ternary operator and case. Two things are different and important: conditionals are expressions that return a value, and they narrow types for the compiler. This lesson covers all of them, including the pattern-matching form case ... in.

Crystal listings are read-only here. Runnable Ruby stand-ins show the same control flow; Ruby 4.0 is close enough that most of it runs unchanged.

if, elsif, else

CRYSTAL
temperature = 28

if temperature > 30
  puts "hot"
elsif temperature > 20
  puts "warm"
else
  puts "cool"
end

There are no parentheses around the condition and no braces; the block ends with end. Use elsif, not else if.

Truthiness

Only two values are false: false and nil. Everything else is true, including 0, "" and [].

CRYSTAL
puts "zero is truthy" if 0
puts "empty string is truthy" if ""
puts "nil is falsey" unless nil

This surprises programmers from C, JavaScript or Python. It is the same as in Ruby.

if as an expression

Every if returns the value of the branch that ran, so you can assign the result:

CRYSTAL
size = 12
label = if size < 10
          "small"
        elsif size < 20
          "medium"
        else
          "large"
        end
puts label    # medium

If a branch is missing and none matches, the result is nil, and the variable's type includes Nil. Add an else when you need a certain value.

Modifier form

A one-line condition can follow the statement:

CRYSTAL
puts "adult" if age >= 18
puts "minor" unless age >= 18

Use it for short, simple conditions. Long ones read better as a block.

unless

unless is if not. Use it for a single negative condition and avoid unless ... else, which is hard to read.

CRYSTAL
unless user.admin?
  puts "access denied"
end

The ternary operator

CRYSTAL
status = count > 0 ? "has items" : "empty"

Keep ternaries short and never nest them.

Boolean operators

&& (and), || (or) and ! (not) are short-circuiting: the right side runs only if needed. The words and, or, not do not exist in Crystal.

CRYSTAL
name = nil
display = name || "guest"      # "guest"
ok = (age >= 18) && has_ticket  # both must hold

|| returns the first truthy value, which makes it a favourite for defaults.

Here is a Ruby stand-in. It runs the same conditions and shows the truthy values and the expression form:

Ruby Stand-in: conditions as expressions in Ruby

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Types are narrowed by conditions

This is what makes Crystal's if special. The compiler uses a condition to learn about a variable's type inside the branch (see union types).

CRYSTAL
def length(value : String | Nil) : Int32
  if value
    value.size        # value is String here
  else
    0
  end
end

The same works with is_a?, nil? and responds_to?.

case / when

case compares one value against several options. It uses the case equality operator ===, which makes it much more powerful than a plain == chain.

CRYSTAL
grade = 87

result = case grade
         when 90..100 then "A"
         when 80...90 then "B"
         when 70...80 then "C"
         else              "F"
         end
puts result    # B

when accepts:

  • values: when 1, when "yes"
  • several values: when 1, 2, 3
  • ranges: when 0..9
  • types: when String, when Int32 | Float64
  • regular expressions: when /^\d+$/
  • conditions with no subject (the case has nothing after it):
CRYSTAL
case
when temperature < 0  then puts "freezing"
when temperature < 20 then puts "mild"
else                       puts "warm"
end

Type branches narrow the variable, exactly like if value.is_a?(String):

CRYSTAL
def describe(x : Int32 | String | Array(Int32))
  case x
  when Int32  then "int #{x + 1}"
  when String then "string #{x.upcase}"
  else             "array of #{x.size}"
  end
end
Ruby Stand-in: case with ranges, types and regex in Ruby

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Pattern matching with case / in

Crystal also has a case ... in form for exhaustive matching, used with enums, unions and tuples. The compiler checks that you covered every possibility.

CRYSTAL
enum Light
  Red
  Yellow
  Green
end

def action(light : Light) : String
  case light
  in .red?    then "stop"
  in .yellow? then "slow down"
  in .green?  then "go"
  end
end

puts action(Light::Green)   # go

If you add Blue to the enum and forget to handle it, the program no longer compiles. With plain case/when you would need an else and the error would be hidden. Use in whenever the set of cases is closed, as with enums and union types.

It works for unions too: list every type the value can have, and the compiler insists that none is forgotten.

CRYSTAL
def kind(x : Int32 | String | Nil) : String
  case x
  in Int32  then "number"
  in String then "text"
  in Nil    then "nothing"
  end
end

puts kind(nil)   # nothing

Common mistakes

  1. Using = instead of ==. if x = 5 assigns and is always truthy; the compiler may warn.
  2. Expecting 0 to be false. It is truthy.
  3. Forgetting that a missing else returns nil.
  4. Writing else if. Crystal has elsif.
  5. Using case on a type with no else and then calling a method on the result, which is nilable.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which values are falsey in Crystal?

    Only false and nil are falsey. 0 and "" are truthy.
  2. 2. What is the value of an if expression with no matching branch and no else?

    It evaluates to nil, so the type of the result includes Nil.
  3. 3. What does case x when 1..5 use to test the value?

    when calls === on the option, so ranges, types and regexes work.
  4. 4. What is the advantage of case ... in over case ... when for an enum?

    case/in is exhaustive, so adding a new enum member without handling it is a compile error.

Summary

  • if/elsif/else, unless, the ternary and modifier forms look like Ruby; conditions are expressions.
  • Only false and nil are falsey.
  • Conditions narrow types, so if value makes a nilable variable safe to use inside.
  • case/when uses === and supports values, ranges, types and regexes.
  • case/in checks exhaustiveness for enums, unions and tuples.

Next: Loops, Ranges and Iteration