views:

124

answers:

2

Hi there,

In Ruby & in RoR I oft find myself testing whether an object exists, then whether an object's properties match some criteria. Like so:

if params[:id] && params[:id].size == 40
  ...do stuff
end

Is there a more efficient way to do this? Something like:

if params[:id].size == 40 rescue false

but without using the rescue?

+12  A: 

With Rails 2.3 you can use Object#try method:

if params[:id].try(:size) == 40
  # do stuff
end

try will return nil when called on nil (with any arguments). Hope that makes sense.

neutrino
Beautiful, just beautiful. Thanks!
btelles
@neutrino Awesome! Didn't know about that at all, great answer. I would +1, but I reached my limit :(
Doug Neiner
you're welcome guys :)
neutrino
60 points for a 5-line answer, not too shabby. :)
btelles
A: 

the andand gem:

require 'andand'

if params.andand.size == 40 ...do stuff end

rogerdpack
good answer, but andand is now built into Rails as "try"
Jonathan Julian
Hmm. They're a bit different, though similar.-r
rogerdpack