元编程访问局部变量 [英] metaprogramming access local variables

查看:83
本文介绍了元编程访问局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Foo
  def initialize
    bar = 10
  end
  fiz = 5
end

是否有可能获得这些局部值(在类之外)?

Is there a possibility to get these local values (outside the class) ?

推荐答案

initialize中的局部变量将丢失.

The local variable in initialize would be lost.

仅在定义该类并记录该类定义的返回值时,您才能在该类之外获取值fiz.

You are able to get the value fiz outside of the class, but only upon defining that class, and recording the return of the definition of the class.

return_of_class_definition = (class A ; fiz = 5 ; end)会将fiz的值分配给该变量.

return_of_class_definition = (class A ; fiz = 5 ; end) would assign the value of fiz to the variable.

您也可以使用binding,但是,这当然意味着要更改班级,这可能是练习所不允许的.

You can also use binding but of course, this means changing the class, which may not be allowed for the exercise.

class A
  bin = 15
  $binding = binding
end

p eval 'bin', $binding

这篇关于元编程访问局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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