Can I reference a lambda from within itself using Ruby?

后端 未结 4 1117
借酒劲吻你
借酒劲吻你 2020-12-28 16:42

I want to be able to call an anonymous lambda from within itself using Ruby. Consider the following recursive block (returns a factorial). I know I can assign it to a variab

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-28 17:32

    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)
    

提交回复
热议问题