Learn/Crystal/4. Making decisions
Lesson 4 of 8
Sign in

Crystal, lesson 4

Making decisions

Programs constantly make choices: is the password long enough, did the player win, is the shop open? Crystal gives you if, unless and case.

Comparisons and boolean operators

OperatorMeaning
== / !=equal / not equal
<, <=, >, >=ordering

2 exercises to try what you just read.

Exercise 1

Letter grade

Press Ctrl Enter or Check to test your code.

Exercise 2

Leap year

Press Ctrl Enter or Check to test your code.

&&
and: both sides must be true
||or: at least one side must be true
!not: flips true and false

&& and || short-circuit: in a && b, Crystal never looks at b if a is already false.

Crystal's idea of truth is simple: false and nil count as false, and everything else is true, including 0 and the empty string "".

if, elsif, else

Note the spelling elsif, and that every if closes with end. Crystal checks the conditions from top to bottom and runs only the first branch that is true.

if is an expression, so it produces a value you can store:

For tiny choices there is the ternary operator, condition ? yes : no, and the suffix form, which reads like English:

unless is the opposite of if: it runs when the condition is false. Use it only for simple conditions; unless ... else gets confusing fast.

case and when

When one value decides between many branches, use case. Each when can list several values, or a range like 4..6 (both ends included):

Under the hood, when 4..6 asks "is dice inside the range 4..6?", which is why ranges, single values and even types work in a when. Like if, a case returns the value of the branch that ran, so label = case dice ... end works too.

Further reading

  • Crystal reference: if
  • Crystal reference: case
  • Crystal reference: Truthy and falsey values

Read a test score and print its letter grade:

  • 90 to 100: A
  • 80 to 89: B
  • 70 to 79: C
  • 60 to 69: D
  • 0 to 59: F
  • below 0 or above 100: Invalid

Input: one line with a whole number. Output: the grade on one line. For 85, print B. A case with ranges fits this perfectly.

A year is a leap year if it is divisible by 4, except years divisible by 100, which are not, unless they are also divisible by 400. So 2024 and 2000 are leap years, but 1900 is not.

Input: one line with a year. Output: leap or common.

temp = 31
if temp > 25
  puts "It's hot!"
elsif temp > 15
  puts "It's mild."
else
  puts "Bring a jacket."
end
advice = if temp > 25
           "Wear a hat"
         else
           "Bring a jacket"
         end
puts "Too hot!" if temp > 35
puts "Not freezing" unless temp < 0
dice = 4
case dice
when 1
  puts "Ouch"
when 2, 3
  puts "Meh"
when 4..6
  puts "Nice roll"
else
  puts "That's not a die"
end