January 2019
Intermediate to advanced
246 pages
5h 23m
English
Sometimes you want to limit options not just to symbols but to a smaller set of possibilities. It can be handy to group variables with a discrete number of values, like the colors of a traffic light or the compass directions, into a specific type. Crystal supports Enums to group related values, specifically when the number of distinct values isn’t too big:
| | enum Direction |
| | North # value 0 |
| | East # value 1 |
| | South # value 2 |
| | West # value 3 |
| | end |
| | |
| | Direction::South # South |
| | Direction::South.value # => 2 |
Enums are stored internally as integers, but showing their names in the code makes them more readable to humans. In the grand scheme of Crystal things, all enums inherit from the base ...
Read now
Unlock full access