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

后端 未结 5 538
说谎
说谎 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 10:18

    There is no built-in way to get a callers binding in Ruby in 1.8.X or 1.9.X.

    You can use https://github.com/banister/binding_of_caller to work around.

    In MRI 2.0 you can use RubyVM::DebugInspector, see: https://github.com/banister/binding_of_caller/blob/master/lib/binding_of_caller/mri2.rb

    Working sample in MRI 2.0:

    require 'debug_inspector'
    
    def bar(symbol)
      RubyVM::DebugInspector.open do |inspector|
        val = eval(symbol.to_s, inspector.frame_binding(2))
        puts "#{symbol}: #{val}"
      end
    end
    
    def foo
      a = 100
      bar(:a)
    end
    
    foo
    # a: 100
    

提交回复
热议问题