ruby中怎么获得变量的字面值?

【字号: 日期:2022-10-15浏览:31作者:雯心

问题描述

比如:v = ’abc’v这个字符串,就是v这个对象的字面值;而’abc‘则是变量v的值。二者不同。我想要得到的是v这个变量的字面值。比如有一个方法m(v),传递参数是v,那么m(v)就返回v。那么这个m方法怎么定义呢?或者说在某个对象上调用m2()方法,代码像这样:v.m2(),这句代码就返回v;如果在f这个变量上调用m2()方法,代码像这样:f.m2(),这句代码就返回f.我要请教的是,这个m2()方法怎么实现?多谢!

问题解答

回答1:

我从stackoverflow上抄来的:

http://stackoverflow.com/questions/2603617/ruby-print-the-variable-name-and-then-its-value

# the function must be defined in such a place# ... so as to 'catch' the binding of the vars ... cheesy# otherwise we’re kinda stuck with the extra param on the caller@_binding = bindingdef write_pair(p, b = @_binding) eval(' local_variables.each do |v| if eval(v.to_s + '.object_id') == ' + p.object_id.to_s + 'puts v.to_s + ’: ’ + '' + p.to_s + '' end end ' , b)end# if the binding is an issue just do here:# write_pair = lambda { |p| write_pair(p, binding) }# just some test vars to make sure it worksusername1 = 'tyndall'username = 'tyndall'username3 = 'tyndall'# the result:write_pair(username)# username: tyndall

相关文章: