Ruby accessing outer variables in nested function

前端 未结 1 1805
暖寄归人
暖寄归人 2020-12-24 11:01

I\'m sure there\'s a simple answer for this; I just can\'t seem to find it. I made a nested function in Ruby, and I was having trouble accessing variables from the outer fun

相关标签:
1条回答
  • 2020-12-24 11:49

    As far as I know, defining a named function within a function does not give you access to any local variables.

    What you can do instead is use a Proc:

    def foo(x)
      bar = lambda do
        puts x
      end
      bar.call
      42
    end
    
    foo(5)
    
    0 讨论(0)
提交回复
热议问题