O'Reilly logo

Mastering Ruby Closures by Benjamin Tan Wei Hao

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required