Last Updated: February 25, 2016
·
603
· depy

Lambda composition in ruby

In order to be able to compose lambdas like in other functional languages we need to add a simple method to Proc class.

class Proc
  def *(f)
    ->(*args) { self.(f.(*args)) }
  end
end

Now we can do:

plus2 = ->(n) { n+2 }
plus3 = ->(n) { n+3 }
plus5 = plus2 * plus3

plus5.(5) # returns 10

Note that notation f.(x) if exactly the same as f.call(x). It's just a bit shorter.