search

Home  >  Q&A  >  body text

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

天蓬老师天蓬老师2778 days ago645

reply all(1)I'll reply

  • ringa_lee

    ringa_lee2017-04-24 09:15:18

    I copied it from 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

    reply
    0
  • Cancelreply