Crystal Control Flow — if, unless, case, while, and until
In this tutorial, you will learn about Crystal Control Flow. We cover key concepts, practical examples, and best practices to help you master this topic.
Crystal's control flow will feel familiar to Ruby developers — but with static typing that catches mistakes at compile time. Every expression returns a value, including if/unless/case.
In this tutorial, you'll learn Crystal's control flow constructs. Crystal compiles to native code, so your control flow is as fast as C's.
What You'll Learn
- if/elsif/else — with return values
- unless for negative conditions
- Ternary operator
- case/when for pattern matching
- while and until loops
- Truthiness in Crystal
if/elsif/else
age = 20
# Expression returns value
status = if age >= 18
"adult"
else
"minor"
end
puts status # => adult
# Single-line
puts "Adult" if age >= 18
# elsif
score = 85
grade = if score >= 90
"A"
elsif score >= 80
"B"
elsif score >= 70
"C"
else
"F"
end
puts grade # => B
unless
temperature = 30
unless temperature > 35
puts "Pleasant weather" # Runs because 30 <= 35
end
# One-liner
puts "Not too hot" unless temperature > 35
Ternary Operator
age = 17
puts age >= 18 ? "Adult" : "Minor"
case/when
def describe(value)
case value
when .zero?
"Zero"
when .positive?
"Positive"
when .negative?
"Negative"
else
"Unknown"
end
end
puts describe(0) # => Zero
puts describe(42) # => Positive
# Type-based matching
def process(value)
case value
when String
"String: #{value.upcase}"
when Int32
"Integer: #{value * 2}"
when Array
"Array: #{value.size} elements"
else
"Unknown type"
end
end
puts process("hello") # => String: HELLO
puts process([1, 2]) # => Array: 2 elements
while and until
# while
i = 0
while i < 5
puts i
i += 1
end
# Output: 0, 1, 2, 3, 4
# until (while !condition)
i = 0
until i == 5
puts i
i += 1
end
# Same output
Truthiness
# Only nil and false are falsy
if 0 # => true (0 is truthy!)
if "" # => true
if nil # => false
if false # => false
Practice Questions
Write a function using case/when to categorize HTTP status codes.
Use while to compute the sum of integers from 1 to N.
Write a function that returns the largest of three numbers using if/elsif.
Use unless to implement a "skip if admin" pattern.
Write a case statement that matches on different types.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro