新手问题 ruby 中怎么实现可变变量

tablecell · October 17, 2019 · Last by sevk replied at October 18, 2019 · 2302 hits

比如


$bj=100;
$sh=200;


$key='bj';

print  $$key;    // 100
$key='sh';
print  $$key ;   // 200 

用 eval, 例如

eval("$#{$key}")

全局变量好像没有好的办法,只能 eval.

像类变量,实例变量,本地变量都有方法。class_variable_get , local_variable_get, instance_variable_get, thread_variable_get

https://devdocs.io/ruby~2.6/module#method-i-class_variable_get

h={}
h['bj']=100;
h['sh']=200;

$key='bj'
print h[key]   

You need to Sign in before reply, if you don't have an account, please Sign up first.