Enums group a related number of values and store the values internally as integers. Enums are good to use when the number of values are not too big.

crystal

# Define an Enum.
enum Bike
  Specialized
  Trek
  Cannondale
  Factor
end

# Access an Enum.
Bikes::Specialized  # => Specialized

# Check the type of an Enum.
typeof(Bike::Specialized) # => Bike

# Access the Enum value
Bike::Specialized.value  # => 0

# Check the type of the Enum value
typeof(Bike::Specialized.value)  # => Int32
    

Considerations

  • Enums are a type safe alternative to Symbols.
  • It is recommended to use Enums whenever possible and only use Symbols for an internal API implementation.

Tags

crystal