Skip to Content
The Ruby Programming Language
book

The Ruby Programming Language

by David Flanagan, Yukihiro Matsumoto
January 2008
Beginner to intermediate
446 pages
14h 45m
English
O'Reilly Media, Inc.
Content preview from The Ruby Programming Language

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

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Metaprogramming Ruby 2

Metaprogramming Ruby 2

Paolo Perrotta

Publisher Resources

ISBN: 9780596516178Supplemental ContentErrata Page