Basics

Crystal Case

Case Expressions

Crystal case expressions handle conditions with pattern matching.

Introduction to Crystal Case Expressions

In Crystal, case expressions provide a powerful way to handle conditional logic through pattern matching. They allow you to compare a single value against multiple patterns and execute code based on the first match found. This feature can simplify complex conditional structures, making your code more readable and maintainable.

Basic Syntax of Case Expressions

The basic syntax of a case expression in Crystal involves the case keyword, followed by the expression to be evaluated. You then list when clauses, each specifying a pattern to match against the expression. An optional else clause can be used to handle cases where no pattern matches.

Example of Case Expression with Integers

Let's consider an example where we use a case expression to determine the category of a number. We will categorize numbers as 'small', 'medium', or 'large' based on their value.

Using Case Expressions with Strings

Case expressions can also be used with strings to match specific values or patterns. In the following example, we use a case expression to print a message based on a user's role.

Advanced Pattern Matching

Crystal case expressions support advanced pattern matching, allowing for more complex conditions. You can match against types, ranges, or even use conditions within a when clause. Below is an example using a case expression to handle different types of inputs.

Conclusion

Crystal's case expressions are a versatile tool for handling conditional logic with pattern matching. They make your code more concise and expressive by allowing you to handle multiple conditions gracefully. As you continue to learn Crystal, mastering case expressions will be essential for writing clean and efficient code.

Previous
If Else
Next
Loops