ruby中怎麼得到變數的字面值?
天蓬老师
天蓬老师 2017-04-24 09:13:18
0
1
640

例如: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 = 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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板