如何检查错误的名称错误

时间:2013-08-21 02:35:59

标签: ruby exception exception-handling

所以我试图从班级的价值中获得一个班级:

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

然而,有时应用程序会让我感到困惑:

NameError: wrong constant name a

所以我假设有一些奇怪的product_name具有nil值或损坏的值:例如a

您如何检查这是否是NameError问题?

说,

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

2 个答案:

答案 0 :(得分: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 :(得分:1)

这太明显了,但以防万一:

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