實(shí)例講解Ruby線程局部域變量
我們知道,在Ruby語(yǔ)言中存在一些內(nèi)置變量,這些變量實(shí)現(xiàn)的功能不盡相同。下面就讓我們一起來(lái)看看有關(guān)Ruby線程局部域的一些介紹。#t#
Ruby線程局部域變量之$!
最近發(fā)生的異常的信息.由raise設(shè)定.
- def exception
- begin
- raise "exception test."
- ensure
- puts $!
- end
- end
- exception
結(jié)果:
- simple.rb:58:in `exception':
exception test. (RuntimeError)- from simple.rb:64
- exception test. # $!中的值
Ruby線程局部域變量之$@
以數(shù)組形式保存著發(fā)生異常時(shí)的back trace信息. 數(shù)組元素是字符串,它顯示了方法調(diào)用的位置,其形式為
"filename:line"或 "filename:line:in `methodname'" 。在向$@賦值時(shí),$!不能為nil。
- def exception
- begin
- raise "exception test."
- ensure
- puts $@
- puts "$@ size is:#{$@.size}"
- end
- end
- exception
結(jié)果:
- simple.rb:58:in `exception':
exception test. (RuntimeError)- from simple.rb:65
- simple.rb:58:in `exception' #$@中的值,
是一個(gè)數(shù)組,第一個(gè)元素是錯(cuò)誤發(fā)生的行數(shù),
第二個(gè)是異常的內(nèi)容。下面打印了數(shù)組的長(zhǎng)度- simple.rb:65
- $@ size:2