O'Reilly logo

Ruby by Example by Kevin C. Baird

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

Chapter 10. More Complex Utilities and Tricks, Part II

image with no caption

In this chapter, I’ll describe an important functional technique called the callback, in which a general-purpose method uses a Proc to determine its specific result. We’ve actually seen this plenty of times before, because it’s built right into many Ruby methods. Let’s say we want to double every number in a list. That’s easy. We just use [0, 1, 2].map { |x| x * 2 } and get [0, 2, 4] as the result. If we want to find all numbers greater than 1, we use [0, 1, 2].find_all { |x| x > 1 } and get [2] instead.

All we’re doing in either case is using a general purpose method like map or find_all that ...

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