Basics

Crystal If Else

Conditional Statements

Crystal if-else statements control flow with Ruby-like expressions.

Introduction to If-Else in Crystal

The if-else statement in Crystal is a fundamental control structure that allows you to execute different blocks of code based on specific conditions. It is similar to the if-else statement in Ruby, providing a familiar syntax for those who have used Ruby before.

Understanding how to effectively use if-else statements is crucial for controlling the flow of your Crystal applications.

Basic Syntax of If-Else

In Crystal, the syntax for an if-else statement is straightforward. Below is the basic structure:

  • if - Introduces a condition.
  • else - Provides an alternative block if the condition is false.
  • end - Ends the if-else block.

Here is a simple example:

Using Else-If for Multiple Conditions

When you need to check multiple conditions, you can use else if (often written as elsif in Ruby and Crystal). This allows you to chain several conditions.

Consider the following example where we determine a person's life stage based on their age:

Ternary If-Else Expression

Crystal also supports a ternary operator for simple if-else conditions. This operator provides a concise syntax for conditional expressions that return a value.

The ternary operator syntax is:

condition ? expr_if_true : expr_if_false

Here is an example:

Conclusion

Mastering the use of if-else statements in Crystal helps control the logical flow of your programs. Whether you use the traditional if-else form or the terse ternary operator, understanding these constructs provides a solid foundation for more complex decision-making processes in your applications.

Now that you've learned about if-else statements, you're ready to explore more advanced control structures, like the Case statement, in the next part of this series.

Previous
Operators
Next
Case