brain/src/dev/ruby/reduce_vs_each_with_object.md

39 lines
739 B
Markdown
Raw Permalink Normal View History

2022-08-14 14:01:33 +00:00
# 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|`