Last Updated: January 12, 2017
·
3.607K
· richrines

Rails: Casting Objects as Arrays

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.

8 Responses
Add your response

Nice tip - thanks!

over 1 year ago ·

Very convenient. Thanks!

over 1 year ago ·

Why not [*param[:emails]]?

over 1 year ago ·

@hauleth Yea, I was wondering why not Array(param[:emails]) -- but the provided link to docs gives a good answer to both your question and mine.

over 1 year ago ·

I find this really helpful. Thanks.

over 1 year ago ·

Pro Tip

over 1 year ago ·

Very succint!

over 1 year ago ·

Cool. Something to remember.

over 1 year ago ·