Control Flow
Here's a simple if statement:
age = 21
if age < 21
puts "You cannot purchase that item."
end
You can chain operators to check within a range:
x = 3
if 2 < x < 5
puts x
end
# => 3
You can define the previous example with logical operators:
x = 3
if 2 < x && x < 5
puts x
end
# = > 3
For more on chaining operators, take a look at the docs.
More complex statement with if/elseif/else:
x = 4
if x < 5
puts "smaller than 5"
elsif x < 8
puts "bigger than 5, smaller than 8"
else
puts "bigger than 8"
end
# => "smaller than 5"
You can assign an if statement to a variable:
x = 7
result = if x < 5
"smaller than 5"
elsif x < 8
"bigger than 5, smaller than 8"
else
"bigger than 8"
end
p result # => "bigger than 5, smaller than 8"
You can use an if statement as a suffix:
x = 3
output = "smaller than 5" if x < 5
p output # => "smaller than 5"
You can use an unless statement for the inverse:
x = 3
output = "smaller than 5" unless x > 5
p output # => "smaller than 5"
Case/When Statements
Use case/when statements for longer and complex expressions where you test the same value against different conditions:
x = 1
output = case x
when 3
"x equals 3"
when 5
"x equals 5"
when 9
"x equals 9"
else
"x is not 3/5/9"
end
p output # => "x is not 3/5/9"
An example of a case/when statement with comparisons:
x = 6
output = case
when x <= 5
"5 or smaller"
when 5 < x < 8
"bigger than 5, smaller than 8"
else
"bigger than 8"
end
p output # => bigger than 5, smaller than 8
Ternary Operator
Crystal has a ternary operator for concise if statements:
user_age = 18
registered = false
output = user_age >= 18 && registered ? "User can vote" : "User cannot vote"
p output # => User cannot vote