Classes
Crystal Enums
Defining Enums
Crystal enums define named constants with values.
What are Enums in Crystal?
Enums in Crystal are a way to define a set of named constants that are associated with unique values. They are particularly useful when you need to represent a limited set of possible options. Enums make your code more readable and maintainable by using descriptive names instead of arbitrary values.
Defining an Enum
To define an enum in Crystal, you use the enum
keyword followed by the enum name and its members. Each member can optionally have an assigned value, but if omitted, Crystal automatically assigns an incrementing integer starting from zero.
Assigning Custom Values
You can assign custom values to enum members. This is useful when the enum values need to correspond to particular data, such as flags or specific codes.
Accessing Enum Values
Once defined, you can access the enum members using the dot notation. Enums also allow you to retrieve the integer value associated with a member using the #to_i
method.
Enum Methods and Iteration
Crystal enums come with built-in methods that make them even more powerful. You can iterate over enum members using the each
method, and you can also convert strings to enum instances using the parse
method.
Enum Use Cases
Enums are ideal for scenarios where you want to represent a fixed set of related constants, such as days of the week, states in a state machine, or specific error codes. They improve code clarity by allowing you to use meaningful names instead of numbers or strings scattered throughout your code.
Classes
- Previous
- Modules as Mixins
- Next
- Arrays