你能在 Ruby 调用者的上下文中评估代码吗? [英] Can you eval code in the context of a caller in Ruby?

查看:27
本文介绍了你能在 Ruby 调用者的上下文中评估代码吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我想知道以下是否可以在 Ruby 中完成.

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

例如:

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

def foo
  a = 100 
  bar(:a) 
end

推荐答案

在 1.8.X 或 1.9.X 的 Ruby 中没有没有内置方法来获取调用者绑定.

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

您可以使用 https://github.com/banister/binding_of_caller 来解决.

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

在 MRI 2.0 中,您可以使用 RubyVM::DebugInspector,请参阅:https://github.com/banister/binding_of_caller/blob/master/lib/binding_of_caller/mri2.rb

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

MRI 2.0 中的工作样本:

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

这篇关于你能在 Ruby 调用者的上下文中评估代码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆