Can I reference a lambda from within itself using Ruby? Can I reference a lambda from within itself using Ruby? ruby ruby

Can I reference a lambda from within itself using Ruby?


In the following example, the lambda is still anonymous, but it has a reference. (Does that pass for anonymous?)

(l = lambda { l.call }).call

(Thanks to Niklas B. for pointing out the error in my original answer; I had only tested it in IRB and it worked there).

This of course ends in a SystemStackError: stack level too deep error, but it demonstrates the purpose.


It seems that anonymous function really doesn't have any reference. You can check it by callee

lambda{ __callee__ }.call #=> nil

And without reference you can't call this function.I can propose to you only a little more clean variant:

(fac = lambda{ |n| n==1 ? 1 : n*fac.call(n-1) }).call(5)


fact = -> (x){ x < 2 ? 1 : x*fact.(x-1)}

minimal function