Rails 3.1: Ruby idiom to prevent .each from throwing exception if nil?
Solution 1
Can't believe no one has suggested this yet:
(@myvar.phonelist || []).each do |phone|
...
If phonelist
is nil
, the each
will loop on the empty array, executing the block zero times.
HOWEVER, this will still throw an exception if phonelist
is not an enumerable (e.g. an array).
Solution 2
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}
Solution 3
Simply do the following:
Array(phonelist).each do |phone|
#deal with your phone
end
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 !
Solution 4
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.
Solution 5
If you get phonelist
from a hash (e.g. parsed JSON file), you may want to use fetch
with []
as the default.
phonelist = my_data.fetch('phonelist', [])
Related videos on Youtube
jpw
Updated on July 06, 2022Comments
-
jpw almost 2 years
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.
-
Andrew Marshall about 12 yearsCalling
each
on an empty enumerable should just do nothing. -
Harish2k22 about 12 years@AndrewMarshall but that's not what's happening, he's calling
each
onnil
. -
Ed S. about 12 years@AndrewMarshall: He meant a
nil
object, not an empty collection. -
jpw about 12 yearsYEP. Thanks. Stupid bug. A helper method was setting to nil not []. Thanks for your comments.
-
Andrew Marshall about 12 yearsThe question states "so it does not throw an error if the object is nil or empty", I was commenting on that fact.
-
Andrew Marshall about 12 years@jpwynn Editing your question with "SOLVED" and an explanation isn't really a good idea. Either accept one of the answers if they solved it, or post your own answer with the solution.
-
-
Ed S. about 12 yearsI guess I don't understand why people resort to something like this when it would be optimal to simply ensure that something that should not ever be nil is not ever nil. If that cannot be done (for whatever reason), why would you do this instead of a simple if statement? I don't get it.
-
johnnyx25 about 12 yearsI agree that it would be optimal to ensure you will never get a nil, but I don't see why adding an if statement is a better solution then using try. Either approach should do the job.
-
johnnyx25 about 12 yearsI guess I don't think having to repeat variable names is clearer or simpler in every situation (especially if long variable names are used), but the nice thing about try is that you can continue to chain together methods without having to break it up with an if. It really depends on the situation of course.
-
Matthew Clark over 10 yearsThis clever and clean, but still just a band-aid. I agree with Ed S. that you should do something different with the object so that it returned something other than nil (like an empty array).
-
idrinkpabst almost 10 yearsI like it. Simple and elegant
-
Yuval Rimar about 5 yearsSometimes you don't control the data structures returned from apis. Things will be nil, the question is valid
-
Ed S. almost 5 yearsOk, then obviously you have to check for null in that situation. Don't see what that has to do with this question.