Update_at
Update At replaces a value at a specific position in a collection.
Overview
update_at replaces a value at a specific index or key.
items | [10, 20, 30] :update_at!(items, 1, 99)
items | [10, 20, 30] :update_at!(items, 1, 99)
Result:
[10, 99, 30]
[10, 99, 30]
Arrays
For arrays, the second argument is an index.
items | [10, 20, 30] :update_at!(items, 2, 42)
items | [10, 20, 30] :update_at!(items, 2, 42)
Result:
[10, 20, 42]
[10, 20, 42]
Maps
For maps, the second argument is a key.
config | {"host": "localhost", "port": "4242"} :update_at!(config, "port", "8080")
config | {"host": "localhost", "port": "4242"} :update_at!(config, "port", "8080")
Result:
{"host": "localhost", "port": "8080"}
{"host": "localhost", "port": "8080"}
Mutation
Like most collection utilities, update_at follows Goblin's bang (!) rules.
:update_atreturns a modified copy:update_at!mutates the original collection
Similar Operations In Other Languages
| JavaScript | Python | Java | C# | Ruby | PHP |
|---|---|---|---|---|---|
| assignment | assignment | set() |
assignment | []= |
assignment |
splice() |
slice assignment | replaceAll() |
Replace() |
replace |
array_replace() |
fill() |
list comprehension | update loop | Select() |
map! |
array_map() |
Update Operator
The |! operator can be used to update a specific collection position.
people | ["daniel", "mike", "harry"] people[0] |! :title(people[0])
people | ["daniel", "mike", "harry"] people[0] |! :title(people[0])
Tip
This also works with basic
update! but you'll need to see how it's done (it's slightly different).
See update.Equivalent to:
:update_at!(people, 0, :title(people[0]))
:update_at!(people, 0, :title(people[0]))
Result:
["Daniel", "mike", "harry"]
["Daniel", "mike", "harry"]
Related Variants
Goblin provides several targeted forms of update:
- update
- update_all
- update_between
- update_first
- update_last
- update_matching
- update_random
- update_where