2013-08-21 13 views
0

所以我試圖讓一個班出班的價值:如何檢查防錯nameerror

 
bucket.product_name.constantize #=> want to check if that fails 

但是有時候應用程序的錯誤我:

 
NameError: wrong constant name a 

所以我假設有一些奇怪的product_name s有nil價值或損壞的價值:如a

你會如何檢查是否是NameError問題?

說,

"a".constantize if "a".constantize != NameError

回答

1
defined?("a") == "constant" 

# => true if "a" is a valid constant name 
# => false otherwise 

使用此:

name = bucket.product_name 
name.constantize if defined?(name) == "constant" 
1

這是太明顯,但以防萬一:

begin 
    "a".constantize 
rescue NameError 
    # handle error here 
end 
+0

感謝您的。絕對是一個很好的答案。不過,我想知道什麼情況可以確定問題 –