Last active
August 29, 2015 14:14
-
-
Save havenwood/cab7ba801d991cbb1307 to your computer and use it in GitHub Desktop.
Composing with Procs
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
class Proc | |
class << self | |
def compose *others | |
others.map(&:to_proc).inject :* | |
end | |
end | |
def * other | |
proc { |*args| other.call self.call *args } | |
end | |
end | |
doubled = ->(n) { n + n } | |
squared = ->(n) { n * n } | |
doubled_then_squared = doubled * squared | |
squared_then_doubled = squared * doubled | |
doubled_then_squared[5] | |
#=> 100 | |
squared_then_doubled[5] | |
#=> 50 | |
do_some_stuff_then_print = Proc.compose doubled_then_squared, | |
:next, | |
squared_then_doubled, | |
method(:puts) | |
do_some_stuff_then_print[5] | |
#>> 20402 | |
#=> nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment