Like many other languages, Crystal has a few methods of controlling a programs flow of execution.

if/elsif/else

if and elsif conditions are evaluated on being truthy or falsy

crystal

# Exampe if/elsif/else block.
if is_stuff
  puts "its stuff"
elsif is_things
  puts "its things"
else
  puts "its something else"
end

# An if condition can be used at the end of an expression.
stuff = "stuff" if is_stuff
    

unless

unless can be though if as a synonym for if not.

crystal

# Exampe unless/else block.
unless is_stuff
  puts "its not stuff, its things"
else
  puts "its stuff"
end

# An unless condition can be used at the end of an expression.
stuff = "stuff" unless not_stuff
    

case/when

case/when blocks are usually more suitable than an if/else block when there is a larger number of conditions to check for.

crystal

# Exampes of case/when block.
items = 10

# Check equality 
how_much_stuff = case items
  when 0
    "no stuff"
  when 1
    "a little stuff"
  when 5
    "a bit more stuff"
  when 10
    "a lot of stuff"
  else
    "maybe get some things"
end
  
# Evaluate expression
how_much_stuff = case
  when items == 0
    "no stuff"
  when 1 < items < 5
    "a little stuff"
  when 5 < items < 10
    "a bit more stuff"
  when items > 10
    "a lot of stuff"
  else
    "maybe get some things"
end
    

Considerations

  • Crystal treats false, nil and null pointers as falsy, everything else is truthy

Tags

crystal