This project is archived and is in readonly mode.

#2364 ✓wontfix
Steven Soroka

ignore_nil{} as a better alternative to try()

Reported by Steven Soroka | March 27th, 2009 @ 09:05 PM | in 2.x

ignore_nil is actually short for "ignore no method error on nil", referring to the error you get if you call a method on an object that is unexpectedly nil. This can happen if you chain method calls together and one of the methods returns a nil.

ignore_nil{} will return nil if you get a NoMethodError exception on NilClass. any other exception type is reraised so that code inside ignore_nil{} blocks don't become a black- hole.

==== Examples

Without ignore_nil:


  @user && @user.address && @user.address.street

or worse:


  @user.address.street rescue nil

(worse because it catches everything! even if address doesn't have a street method!)

With ignore_nil:


  ignore_nil { @user.address.street }

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

People watching this ticket

Attachments

Pages