Last active
November 20, 2019 23:14
-
-
Save KamilLelonek/eda2a5476d6e8dc1c351 to your computer and use it in GitHub Desktop.
Currying functions in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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