Object.try

使用try(rails 2.3)执行某个方法时,你不必担心会抛出NoMethodError异常。如果方法不存在或者对象为空,则会返回nil而不是抛出异常。

 

# No exceptions when receiver is nil
nil.try(:destroy) #=> nil

# Useful when chaining potential nil items
User.admins.first.try(:address).try(:reset)

你可能感兴趣的:(object)