Today I Learned

A Zero One initiative

Fun with Recursive Anonymous Functions

Did you know that an anonymous function can call itself?

All you need is something like this:

factorial_of = -> (n) { n <= 1 ? 1 : n * factorial_of.call(n - 1) }
factorial_of.call(5)
# => 120

This came in handy when I had a recursive method which needed to be wrapped inside an enumerator to navigate a very complex hierarchy of objects.

Instead of something as complex as that, let’s wrap our anonymous factorial function around an enumerator:

factorial_of = -> (n) { n <= 1 ? 1 : n * factorial_of.call(n - 1) }

f = Enumerator.new do |y|
  num = 0
  loop do
    y << factorial_of.call(num)
    num += 1
  end
end

f.next
=> 1
f.next
=> 1
f.next
=> 2
f.next
=> 6

Now we can fetch the next number whenever we want, or enumerate over the numbers until we don’t have any left (which is infinite in this case)

Looking for help? Each developer at Zero One has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.