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

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


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 = nilphonelist.try(:each){|i| puts i}


Simply do the following:

Array(phonelist).each do |phone|  #deal with your phoneend

Array(my_variable) will ensure to return an array if my_variable is nil.

It doesn't create a new Array if my_variable is already an array, so it is safe and light to use it wherever you want !


You're attempting to smack a band-aid on a larger problem.

Ruby has a concept of nil; can't get around it. If you are calling a method on nil, then you are assuming it is valid, i.e., your design assumes it to be valid. So the question really is: where is the hole in your design? Why is your assumption incorrect?

The problem here is not that you cannot call arbitrary methods on an object which does not support it; the problem is that your data is assumed to be valid when obviously that is not always the case.

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

No. If phonelist is not an object which implements .each it throws an error. Very different.

You can always initialize it to an empty array if null, i.e., phonelist ||= [], but I would prefer a design which ensures valid data whenever possible.