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 square_it, double_it |
|
puts double_then_square.call(5) |
puts square_then_double.call(5) |
100 |
50 |
(Notice that the call to proc1 had to be inside the parentheses for proc2 in order for it to run first.)
3.133.142.2