Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add documentation for enum predicate methods #816

Merged
merged 8 commits into from
Feb 6, 2025
Merged
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 43 additions & 6 deletions docs/syntax_and_semantics/enum.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,23 +97,60 @@ puts Color.new(10) # => prints "10"

This method is mainly intended to convert integers from C to enums in Crystal.

## Methods
## Question methods

Just like a class or a struct, you can define methods for enums:
An enum automatically defines question methods for each member, using
`String#underscore` for the method name.

!!! note
In the case of regular enums, this compares by equality (`==`). In the case of flags enums, this invokes `includes?`.

For example:

```crystal
enum Color
Red
Green
Blue
end

color = Color::Blue
color.red? # => false
color.blue? # => true

@[Flags]
enum IOMode
Read
Write
Async
end

def red?
self == Color::Red
mode = IOMode::Read | IOMode::Async
mode.read? # => true
mode.write? # => false
mode.async? # => true
```

## Methods

Just like a class or a struct, you can define methods for enums:

```crystal
enum ButtonSize
Sm
Md
Lg

def label
case self
in .sm? then "small"
in .md? then "medium"
in .lg? then "large"
end
end

Color::Red.red? # => true
Color::Blue.red? # => false
ButtonSize::Sm.label # => "small"
ButtonSize::Lg.label # => "large"
```

Class variables are allowed, but instance variables are not.
Expand Down
Loading