O'Reilly logo

Mastering Ruby Closures by Benjamin Tan Wei Hao

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Currying with Procs

The word “curry” comes from the mathematician Haskell Curry. (I am resisting all attempts to make a lame joke about an Indian dish.) In functional programming, currying is the process of turning a function that takes n arguments into one that takes a single argument, but returns n functions that take one argument.

For example, given a lambda that accepts three parameters:

 >>​ discriminant = lambda { |a, b, c| b**2 - 4*a*c }
 
 >>​ discriminant.call(5, 6, 7)
 =>​ -104

you could convert it into this:

 >>​ discriminant = lambda { |a| lambda { |b| lambda { |c| b **2 - 4*a*c } } }
 
 >>​ discriminant.call(5).call(6).call(7)
 =>​ -104

In Ruby, there’s a shorter way to do this using Proc#curry:

 >>​ discriminant = ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required