搜索

首页  >  问答  >  正文

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()方法怎么实现?
多谢!

天蓬老师天蓬老师2775 天前642

全部回复(1)我来回复

  • ringa_lee

    ringa_lee2017-04-24 09:15:18

    我从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

    回复
    0
  • 取消回复