Functional Programming
Ruby is not a functional programming language in the way that
languages like Lisp and Haskell are, but Ruby’s blocks, procs, and
lambdas lend themselves nicely to a functional programming style. Any
time you use a block with an Enumerable
iterator like map
or inject
, you’re programming in a functional
style. Here are examples using the map
and inject
iterators:
# Compute the average and standard deviation of an array of numbers mean = a.inject {|x,y| x+y } / a.size sumOfSquares = a.map{|x| (x-mean)**2 }.inject{|x,y| x+y } standardDeviation = Math.sqrt(sumOfSquares/(a.size-1))
If the functional programming style is attractive to you, it is easy to add features to Ruby’s built-in classes to facilitate functional programming. The rest of this chapter explores some possibilities for working with functions. The code in this section is dense and is presented as a mind-expanding exploration, not as a prescription for good programming style. In particular, redefining operators as heavily as the code in the next section does is likely to result in programs that are difficult for others to read and maintain!
This is advanced material and the code that follows assumes familiarity with Chapter 7. You may, therefore, want to skip the rest of this chapter the first time through the book.
Applying a Function to an Enumerable
map
and inject
are two of
the most important iterators defined by Enumerable
. Each expects a block. If we are to write programs in a function-centric way, ...
Get The Ruby Programming Language 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.