Implementing Enumerable#reduce (or Fold Left)

Now that you know what closures and first-class functions are, let’s put your new skills to the test. We will conclude this chapter by learning how to implement the reduce method. Ruby already has an implementation in the Enumerable class. However, for our purposes, we are only going to use lambdas.

reduce (sometimes known as fold left) is one of the operations that can be found in almost every functional programming language. In fact, it is so useful that many other non-functional languages have adopted it as part of the standard library.

Let’s do a quick refresher on how reduce works. It needs an array, a binary operation—an operation that takes two operands—and a starting value, commonly known ...

Get Mastering Ruby Closures now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.