Crystal, lesson 4
Programs constantly make choices: is the password long enough, did the player win, is the shop
open? Crystal gives you if, unless and case.
| Operator | Meaning |
|---|---|
== / != | equal / not equal |
<, <=, >, >= | ordering |
2 exercises to try what you just read.
&& |
| 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, elseNote 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 whenWhen 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.
Read a test score and print its letter grade:
90 to 100: A80 to 89: B70 to 79: C60 to 69: D0 to 59: F0 or above 100: InvalidInput: 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."
endadvice = if temp > 25
"Wear a hat"
else
"Bring a jacket"
endputs "Too hot!" if temp > 35
puts "Not freezing" unless temp < 0dice = 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