21 June 2007 Norbert Crombach and Manfred Stienstra

Function composition is a common concept in functional programming languages. This first episode of ‘Ruby Banter’ shows you how to do it in Ruby.

Download episode

# Contains code by Eric Kidd, Peter Burns, and Ola Bini

def op(str)
  lambda { |n| eval(str) }
end

def complement(f = nil, &b)
  b ||= f
  lambda { |*args| !b.call(*args) }
end

def compose(*a)
  a.map! { |b| b.to_proc }

  if a.length == 2

    # this is where it all happens, the rest is recursion
    lambda { |*args| a[0].call(a[1].call(*args)) }

  elsif a.length > 2
    compose(a.shift, compose(*a))
  else
    lambda { nil }
  end
end

def conjoin(*a)
  lambda { |*args| a.all? { |f| f.call(*args) } }
end

def disjoin(*a)
  lambda { |*args| a.any? { |f| f.call(*args) } }
end