Skip to content

Commit 687e4c5

Browse files
committed
Add Check List Membership as an elixir til
1 parent bf8bc28 commit 687e4c5

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
1010
For a steady stream of TILs from a variety of rocketeers, checkout
1111
[til.hashrocket.com](https://til.hashrocket.com/).
1212

13-
_781 TILs and counting..._
13+
_782 TILs and counting..._
1414

1515
---
1616

@@ -123,6 +123,7 @@ _781 TILs and counting..._
123123
- [Assert An Exception Is Raised](elixir/assert-an-exception-is-raised.md)
124124
- [Binary Representation Of A String](elixir/binary-representation-of-a-string.md)
125125
- [Check For A Substring Match](elixir/check-for-a-substring-match.md)
126+
- [Check List Membership](elixir/check-list-membership.md)
126127
- [Comparing DateTime Structs](elixir/comparing-datetime-structs.md)
127128
- [Compute md5 Digest Of A String](elixir/compute-md5-digest-of-a-string.md)
128129
- [Counting Records With Ecto](elixir/counting-records-with-ecto.md)

elixir/check-list-membership.md

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Check List Membership
2+
3+
You can use the [`in` operator](https://hexdocs.pm/elixir/operators.html) to
4+
check if something appears in a list. This is a handy way of checking if a
5+
variable is one of a few acceptable or expected values.
6+
7+
For instance, a common DateTime comparison pattern relies on this to check
8+
if a DateTime is `>=` or `<=` to another DateTime.
9+
10+
```elixir
11+
{:ok, datetime} = DateTime.from_naive(~N[2016-05-24 13:26:08.003], "Etc/UTC")
12+
13+
DateTime.compare(datetime, DateTime.utc_now()) in [:lt, :eq]
14+
```
15+
16+
Alternatively, you can check that something does not have membership in a
17+
list by also including the `not` operator.
18+
19+
```elixir
20+
DateTime.compare(datetime, DateTime.utc_now()) not in [:lt, :eq]
21+
```

0 commit comments

Comments
 (0)