RT 貌似只有 global_variables 定义在 Kernel 里 是不是啊。。。
可以的...
require 'rbconfig'
require 'fiddle'
libruby = Fiddle.dlopen RbConfig::CONFIG['libdir'] + '/' + RbConfig::CONFIG['LIBRUBY_SO']
rb_gv_get = Fiddle::Function.new libruby['rb_gv_get'], [Fiddle::TYPE_VOIDP], Fiddle::TYPE_VOIDP
$x = 3
$y = 'a'
puts rb_gv_get.('$x').to_value
puts rb_gv_get.('$y').to_value
#2 楼 @iBachue local_variables 的取法才 evil…… 单纯 global_variables 还好…… (不过也没有检测变量名)
def gv_get(a)
eval a.to_s
end
def gv_set(a, b)
eval "#{a}=b"
end
def lv_get(a, binding = nil, &block)
eval a.to_s, binding || block.binding
end
def lv_set(a, b, binding = nil, &block)
eval "#{a}=ObjectSpace._id2ref(#{b.object_id})", binding || block.binding
end
gv_set(:$a, 3)
gv_get(:$a)
a = 3
p lv_get(:a){}
lv_set(:a, 5){}
p a
r = lambda{
a = 3
b = 5
binding
}.call
p lv_get(:a, r) + lv_get(:b, r)