Crystal Notes: Control Flow
Published: 29th of July 2021
Like many other languages, Crystal has a few methods of controlling a programs flow of execution.
if and elsif conditions are evaluated on being truthy or falsy
# 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 can be though if as a synonym for if not.
# 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 blocks are usually more suitable than an if/else block when there is a larger number of conditions to check for.
# 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
- Crystal treats false, nil and null pointers as falsy, everything else is truthy