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

查看:103
本文介绍了ruby中怎么获得变量的字面值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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

解决方案

我从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 = binding
def 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 works
username1 = "tyndall"
username  = "tyndall"
username3 = "tyndall"

# the result:
write_pair(username)
# username: tyndall

这篇关于ruby中怎么获得变量的字面值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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