Rails: Casting Objects as Arrays

Posted on

I’ve run across Rails code like the following several times:

def emails
  # force emails into an array if not already in one
  if params[:email].nil?
    []
  elsif params[:emails].is_a String
    [params[:emails]]
  else
    params[:emails]
  end
end

def do_something
  emails.each do |email|
    # do something
  end
end

The above code gets the job done but it’s not very clean.

It can be easily improved with the following:

def emails
  Array.wrap(params[:emails])
end

def do_something
  emails.each do |email|
    # do something
  end
end

Casting anything to an array will return an array. We now no longer care if a string
or an array comes through from the params we are covered in both cases. It’s a cleaner
solution that saves us a few lines as well. This pattern is an example of “Don’t
duplicate the functionality of a built-in library” from our guides. It’s also worth checking out the docs for why #wrap is being used here vs Kernel#Array.

Leave a Reply

Your email address will not be published.