diff --git a/src/SUMMARY.md b/src/SUMMARY.md index aad20fc..4983389 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -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) diff --git a/src/dev/ruby/reduce_vs_each_with_object.md b/src/dev/ruby/reduce_vs_each_with_object.md new file mode 100644 index 0000000..e5bcdd3 --- /dev/null +++ b/src/dev/ruby/reduce_vs_each_with_object.md @@ -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|`