NoMethodError on nil.each?

Have you ever have to iterate over an array from say the params hash? You probably have added some code to make sure that data exists in the hash element first before doing the loop. This is a cool little trick to help condense some code. Normally I would write this:

if params[:accounts] and params[:accounts].size > 0
  params[:accounts].each do |account|
    # Do something with account here

As you can see, kind of ugly. Here is the change:

(params[:accounts] || []).each do |account|
  # Do something with account

AHH!!! Much nicer!

You have a nil object when you didn’t expect it!

I found this cool little snippet of code somewhere on the internet. Anywhere you access an object in a view, adding the following will ensure the page doesn’t blow up:

<%= @object.association.variable rescue nil %>

Of course, you won’t know if you have an error now either.

%d bloggers like this: