File: sum.html.md

package info (click to toggle)
ruby-dry-types 1.2.2-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 504 kB
  • sloc: ruby: 3,059; makefile: 4
file content (21 lines) | stat: -rw-r--r-- 598 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
---
title: Sum
layout: gem-single
name: dry-types
order: 7
---

You can specify sum types using `|` operator, it is an explicit way of defining what the valid types of a value are.

For example `dry-types` defines the `Bool` type which is a sum consisting of the `True` and `False` types, expressed as `Types::True | Types::False`.

Another common case is defining that something can be either `nil` or something else:

``` ruby
nil_or_string = Types::Nil | Types::String

nil_or_string[nil] # => nil
nil_or_string["hello"] # => "hello"

nil_or_string[123] # raises Dry::Types::ConstraintError
```