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

后端 未结 5 539
说谎
说谎 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:11

    You have to pass foo's context to bar:

    def foo
      a = 100
      bar(:a, binding)
    end
    def bar(sym, b)
      puts "#{sym} is #{eval(sym.to_s, b)}"
    end
    

提交回复
热议问题