Rails 3.1: Ruby idiom to prevent .each from throwing exception if nil?

jpw picture jpw · Mar 7, 2012 · Viewed 16.7k times · Source

Is there a way to use .each so it does not throw an error if the object is nil or empty (without adding an additional nil/blank test?

It seems that if I say phonelist.each do |phone| that if phonelist is empty, then the block should not be executed.

But in my view (haml) I have - @myvar.phonelist.each do |phone| and if phonelist is empty, it throws a NoMethodError.

I run into this a lot, and always workaround by adding an explicit check/branch for .blank? but it seems there should be an easier way to tell .each that empty means do nothing.

Answer

johnnyx25 picture johnnyx25 · Mar 7, 2012

You can use the try method to call .each on a nil so it does not throw an error if the object is nil or empty.

phonelist = nil
phonelist.try(:each){|i| puts i}