Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active August 29, 2015 14:14
Show Gist options
  • Save havenwood/cab7ba801d991cbb1307 to your computer and use it in GitHub Desktop.
Save havenwood/cab7ba801d991cbb1307 to your computer and use it in GitHub Desktop.
Composing with Procs
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