Skip to Main Content
Learn to Program, 2nd Edition
book

Learn to Program, 2nd Edition

by Chris Pine
March 2009
Intermediate to advanced content levelIntermediate to advanced
194 pages
4h
English
Pragmatic Bookshelf
Content preview from Learn to Program, 2nd Edition

Methods That Return Procs

One of the cool things you can do with procs is create them in methods and return them. This allows all sorts of crazy programming power (things with impressive names, such as lazy evaluation, infinite data structures, and currying). I don’t actually do these things very often, but they are just about the sexiest programming techniques around.

In this example, compose takes two procs and returns a new proc that, when called, calls the first proc and passes its result into the second:

def​ compose proc1, proc2
Proc.new ​do​ |x|
proc2.call(proc1.call(x))
end
end
square_it = Proc.new ​do​ |x|
x * x
end
double_it = Proc.new ​do​ |x|
x + x
end
double_then_square = compose double_it, square_it
square_then_double = compose ...
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

Learn to Program, 3rd Edition

Learn to Program, 3rd Edition

Chris Pine
The Book of Ruby

The Book of Ruby

Huw Collingbourne

Publisher Resources

ISBN: 9781680500172Errata