Can you eval code in the context of a caller in Ruby?

后端 未结 5 532
说谎
说谎 2020-12-06 09:46

Essentially I\'m wondering if the following can be done in Ruby.

So for example:

def bar(symbol) 
  # magic code goes here, it outputs \"a = 100\"          


        
5条回答
  •  旧巷少年郎
    2020-12-06 09:56

    Check article out Variable Bindings in Ruby

    class Reference
      def initialize(var_name, vars)
        @getter = eval "lambda { #{var_name} }", vars
        @setter = eval "lambda { |v| #{var_name} = v }", vars
      end
      def value
        @getter.call
      end
      def value=(new_value)
        @setter.call(new_value)
      end
    end
    
    def ref(&block)
      Reference.new(block.call, block.binding)
    end
    
    def bar(ref)
      # magic code goes here, it outputs "a = 100" 
      p ref.value
    end
    
    def foo
      a = 100 
      bar(ref{:a}) 
    end
    
    foo
    

提交回复
热议问题