Recursive blocks/procs/lambdas in Ruby

I need to start doing more “quick-fire” posts of cool things I find, rather than saving up big-ticket items that never get posted. Anyway…

I just had an interesting coding problem where I needed to have a quick recursive function in Ruby on Rails and I didn’t want to move it into it’s own method. A lambda or proc would have been perfect but it needed to be recursive (and “how can you self-reference a lambda” I thought?). Well it turns out it’s not that hard. It seems that variables defined outside of a lambda are still in-scope inside of the lambda.

I learned how to do this from Josh Susser, who has a Ruby on Rails specific example.


Here is a simple example to calculate factorials using a lambda:

factorial = lambda do |n|
  n <= 1 ? 1 : (n * - 1))



About this entry