Lesson 6 of 16

Case Expressions

case

The case expression matches a value against a series of patterns:

n = 2
result = case n do
  1 -> "one"
  2 -> "two"
  _ -> "other"
end
IO.puts(result)   # two

The _ wildcard matches anything.

Matching Atoms

case works great with atom results:

day = :saturday
result = case day do
  :monday -> "weekday"
  :tuesday -> "weekday"
  :saturday -> "weekend"
  :sunday -> "weekend"
  _ -> "weekday"
end
IO.puts(result)   # weekend

Your Turn

  1. Match n = 2 in a case, print "two"
  2. Match day = :saturday in a case, print "weekend"
JS Transpiler loading...
Loading...
Click "Run" to execute your code.