Add reduce vs each with index note

This commit is contained in:
Wilfried OLLIVIER 2022-08-14 16:01:33 +02:00
parent 2bdfa5a22f
commit 2b242e2254
2 changed files with 39 additions and 0 deletions

View File

@ -17,6 +17,7 @@
- [Testing](./dev/rust/testing.md)
- [Ruby](./dev/ruby/main.md)
- [arrays](./dev/ruby/arrays.md)
- [reduce vs each_with_object](./dev/ruby/reduce_vs_each_with_object.md)
- [TypeScript](./dev/ts/main.md)
- [interfaces](./dev/ts/interfaces.md)
- [decorators](./dev/ts/decorators.md)

View File

@ -0,0 +1,38 @@
# Reduce vs Each With Object
Both methods serve the same purpose : from an Enumerator create a single value
out of it
## Reduce
Reduce is prefered when you need to produce a simple value because it reduce over the returned value
```ruby
[1, 2, 3].reduce(:+)
> 3
```
We can illustrate this simply with this snippet :
```ruby
[1, 2, 3].reduce do |acc, v|
acc += v
0
end
> 0
```
## Each With Object
Each with object is prefered when you reduce on a hash or some sort of complex
object beacause is use the accumulator value and not the returned one
```ruby
[1, 2, 3].each_with_object({ sum: 0 }) do |v, acc|
acc[:sum] += v
0
end
> {sum: 6}
```
**Fun fact**, `reduce` takes `|acc, v|` while `each_with_object` take `|v, acc|`