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 ... |
Get Learn to Program, 2nd Edition 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.