搜尋

首頁  >  問答  >  主體

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()方法要怎麼實現?
多謝!

天蓬老师天蓬老师2865 天前687

全部回覆(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
  • 取消回覆