Skip to content

Instantly share code, notes, and snippets.

@JamesKyburz
Created August 9, 2011 10:02
Show Gist options
  • Save JamesKyburz/1133700 to your computer and use it in GitHub Desktop.
Save JamesKyburz/1133700 to your computer and use it in GitHub Desktop.
Composed in Ruby
module Kernel
def composed(actions)
lambda do |*args, &block|
actions.reverse.reduce(*args) do |result, next_op|
result = next_op.call(result, &block)
end
end
end
end
class Class
def composed_method(name, actions, *options)
if options.include?(:class_method)
define_singleton_method name, &composed(actions)
else
define_method name, &composed(actions)
end
end
end
class Ops
def self.plus_one(x)
x + 1
end
def self.times_two(x)
x * 2
end
def self.sq(x)
x * x
end
composed_method :all_of_the_above, [:plus_one, :times_two, :sq].map { |x| method(x) }, :class_method
end
methods = [:plus_one, :times_two, :sq]
methods.map! { |x| Ops.method(x) }
methods # => [#<Method: Ops.plus_one>, #<Method: Ops.times_two>, #<Method: Ops.sq>]
composed(methods).call(1) # => 3
composed(methods).call(2) # => 9
composed(methods).call(3) # => 19
plus_one = -> x { x + 1}
times_two = -> x { x * 2}
sq = -> x { x * x}
methods = [plus_one, times_two, sq] # => [#<Proc:0x007fd58c046fa0@-:42 (lambda)>, #<Proc:0x007fd58c046f78@-:43 (lambda)>, #<Proc:0x007fd58c046f50@-:44 (lambda)>]
composed(methods).call(1) # => 3
composed(methods).call(2) # => 9
composed(methods).call(3) # => 19
Ops.all_of_the_above(1) # => 3
Ops.all_of_the_above(2) # => 9
Ops.all_of_the_above(3) # => 19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment