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

Get Ruby by Example now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.