March 2009
Intermediate to advanced
194 pages
4h
English
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 ... |