Cleaning up submitted emails in Ruby

So there I was the other day, adding a feature where users could invite their friends to join Fluency too. The UI is a textarea where the user is asked to enter the email addresses on separate lines, so that’s pretty simple to grab the emails from:
recipients = params[:contact_emails].split(/\s/)

But because the line separator is actually two characters (newline and carriage return) you end up with empty elements in the returned array:
["someone@example.com","","something@gmail.com"]

Enter Ruby; by passing a block to the array, it can test for empty strings and reject them:

and then use a similar technique by passing a block to the array of cleaned strings to verify that they are indeed emails. The snippet above is a simple test – ensuing that there is a dot and an @ sign with at least one character surrounding them in the right order.

Related

Post navigation

Ian Anderson

I’m a hands-on product person who loves working in startups and agile software teams to help define, design and build great web applications that people find useful and enjoy using. I’ve built several products aimed at online learning and employability, and am keenly interested in “tech for good” and building significant online products for ethical or social businesses.