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
.
Written by richrines
Related protips
8 Responses

Nice tip - thanks!
over 1 year ago
·

Very convenient. Thanks!
over 1 year ago
·

Why not [*param[:emails]]
?
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#