February 3, 2008

function composition in Ruby

Here is an easy way to compose functions:

#!/usr/bin/env ruby

# method composition example
# > require 'compose'
# > (method(:multwo) << method(:multwo) << method(:add)).call(2,3)
# => 20

class Proc
def << g
lambda {|*args| self.call(g.call(*args)) }
end
end

class Method
def << g
lambda {|*args| self.call(g.call(*args)) }
end

end

def add left, right
left + right
end

def multwo arg
arg * 2
end

0 comments: