Change the binding of a Proc in Ruby

后端 未结 4 1516
春和景丽
春和景丽 2020-12-15 05:48

I have this code:

 l = lambda { a }
 def some_function
     a = 1
 end

I just want to access a by the lambda and a special sco

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-15 06:47

    Perhaps you don't actually need to define a later, but instead only need to set it later.

    Or (as below), perhaps you don't actually need a to be a local variable (which itself references an array). Instead, perhaps you can usefully employ a class variable, such as @@a. This works for me, by printing "1":

    class SomeClass
      def l
        @l ||= lambda { puts @@a }
      end
    
      def some_function
        @@a = 1
        l.call
      end
    end
    SomeClass.new.some_function
    

提交回复
热议问题