You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: lib/elixir/pages/getting-started/keywords-and-maps.md
+19-15Lines changed: 19 additions & 15 deletions
Original file line number
Diff line number
Diff line change
@@ -11,44 +11,48 @@ Keyword lists are a data-structure used to pass options to functions. Let's see
11
11
Imagine you want to split a string of numbers. Initially, we can invoke `String.split/2` passing two strings as arguments:
12
12
13
13
```elixir
14
-
iex>String.split("1 2 3", "")
15
-
["1", "2", "3"]
14
+
iex>String.split("1 2 3 4", "")
15
+
["1", "2", "3", "4"]
16
16
```
17
17
18
-
However, what happens if there is an additional space between the numbers:
18
+
What if you only want to split at most 2 times? The `String.split/3` function allows the `parts` option to be set to the maximum number of entries in the result:
19
19
20
20
```elixir
21
-
iex>String.split("1 2 3", "")
22
-
["1", "", "2", "", "3"]
21
+
iex>String.split("1 2 3 4", "", [parts:3])
22
+
["1", "2", "3 4"]
23
23
```
24
24
25
-
As you can see, there are now empty strings in our results. Luckily, the `String.split/3` function allows the `trim` option to be set to true:
25
+
As you can see, we got 3 parts, the last one containing the remaining of the input without splitting it.
26
+
27
+
Now imagine that some of the inputs you must split on contains additional spaces between the numbers:
26
28
27
29
```elixir
28
-
iex>String.split("1 2 3", "", [trim:true])
29
-
["1", "2", "3"]
30
+
iex>String.split("1 2 3 4", "", [parts:3])
31
+
["1", "", "2 3 4"]
30
32
```
31
33
32
-
We can also use options to limit the splitting algorithm to a maximum number of parts, as shown next:
34
+
As you can see, the additional spaces lead to empty entries in the output. Luckily, we can also set the `trim` option to `true` to remove them:
`[trim: true]` and `[trim: true, parts: 2]` are keyword lists. When a keyword list is the last argument of a function, we can skip the brackets and write:
41
+
Once again we got 3 parts, with the last one containing the leftovers.
42
+
43
+
`[parts: 3]` and `[parts: 3, trim: true]` are keyword lists. When a keyword list is the last argument of a function, we can skip the brackets and write:
As shown in the example above, keyword lists are mostly used as optional arguments to functions.
47
51
48
52
As the name implies, keyword lists are simply lists. In particular, they are lists consisting of 2-item tuples where the first element (the key) is an atom and the second element can be any value. Both representations are the same:
0 commit comments