Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Currying functions in Ruby
[1] (pry) main: 0> add = -> (a, b) { a + b }
=> #<Proc:0x007ffde11d72c0@(pry):1 (lambda)>
# Call proc with two arguments
[2] (pry) main: 0> add.(1, 2)
=> 3
# Call proc with one argument
[3] (pry) main: 0> add.(1)
ArgumentError: wrong number of arguments (1 for 2)
from (pry):1:in `block in __pry__`
# Curry add function
[4] (pry) main: 0> add_curry = add.curry
=> #<Proc:0x007ffde300d9d8 (lambda)>
# Create partial function with one argument applied
[5] (pry) main: 0> increment = add_curry.(1)
=> #<Proc:0x007ffde122dcd8 (lambda)>
[6] (pry) main: 0> increment.(2)
=> 3
# Different ways to call curried function
[7] (pry) main: 0> add_curry.(1).(2)
=> 3
[8] (pry) main: 0> add_curry.(1, 2)
=> 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment