If Else in Crystal

Branching with if and else in Crystal is straightforward.

# Here's a basic example.
if 7 % 2 == 0
  puts "7 is even"
else
  puts "7 is odd"
end

# You can have an `if` statement without an else.
if 8 % 4 == 0
  puts "8 is divisible by 4"
end

# Logical operators like `&&` and `||` are often useful in conditions.
if 8 % 2 == 0 || 7 % 2 == 0
  puts "either 8 or 7 are even"
end

# A statement can precede conditionals; any variables
# declared in this statement are available in the current
# and all subsequent branches.
if num = 9
  if num < 0
    puts "#{num} is negative"
  elsif num < 10
    puts "#{num} has 1 digit"
  else
    puts "#{num} has multiple digits"
  end
end

To run the program, save it as if_else.cr and use the Crystal compiler:

$ crystal if_else.cr
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Note that you don’t need parentheses around conditions in Crystal, but the end keyword is required to close each block.

Crystal doesn’t have a ternary operator like some other languages, so you’ll need to use a full if statement even for basic conditions. However, Crystal does have a shorthand syntax for simple if-else statements:

result = if condition
           value_if_true
         else
           value_if_false
         end

This syntax can be used for simple conditional assignments.