實例講解Ruby線程局部域變量
作者:佚名
Ruby線程局部域變量痛其他變量一樣都是以$開頭。比如:$!和$@等。一般情況下是用來處理異常等的操作。下面將會對此做詳細介紹。
我們知道,在Ruby語言中存在一些內置變量,這些變量實現的功能不盡相同。下面就讓我們一起來看看有關Ruby線程局部域的一些介紹。#t#
Ruby線程局部域變量之$!
最近發生的異常的信息.由raise設定.
- def exception
- begin
- raise "exception test."
- ensure
- puts $!
- end
- end
- exception
結果:
- simple.rb:58:in `exception':
exception test. (RuntimeError)- from simple.rb:64
- exception test. # $!中的值
Ruby線程局部域變量之$@
以數組形式保存著發生異常時的back trace信息. 數組元素是字符串,它顯示了方法調用的位置,其形式為
"filename:line"或 "filename:line:in `methodname'" 。在向$@賦值時,$!不能為nil。
- def exception
- begin
- raise "exception test."
- ensure
- puts $@
- puts "$@ size is:#{$@.size}"
- end
- end
- exception
結果:
- simple.rb:58:in `exception':
exception test. (RuntimeError)- from simple.rb:65
- simple.rb:58:in `exception' #$@中的值,
是一個數組,第一個元素是錯誤發生的行數,
第二個是異常的內容。下面打印了數組的長度- simple.rb:65
- $@ size:2
責任編輯:曹凱
來源:
javaeye.com