How does inject (reduce) work in Ruby, and how do you use it?
Last updated
inject(aliasreduce) folds a collection into one value. The block gets (memo, element) and its return value becomes the next accumulator (memo).A seed like
inject(0)sets the starting memo. Without one, the first element is used and an empty collection returnsnil.Symbol shorthand applies an operator between elements:
inject(:+)or with a seedinject(1, :*).
- https://www.railscarma.com/blog/ruby-inject-and-ruby-reduce/
- https://docs.ruby-lang.org/en/3.1/Enumerable.html
- https://docs.ruby-lang.org/en/master/Enumerable.html
- https://medium.com/@janetmndz/understanding-rubys-inject-reduce-enumerable-methods-in-under-5-minutes-193e5cff06d0
- https://www.gingertechblog.com/ruby-reduce-method/
- https://dev.to/jrrohrer/ruby-reduce-cob
- https://thoughtbot.com/blog/how-to-approach-a-reduce-problem