Search code examples
ruby-on-railsparsingsplitcloudmailin

Stop parsing when hitting an empty line


I have a Rails app parsing incoming e-mails on Heroku using the Cloud-mailin add-on. The app recieves a list of prices in an e-mail and inserts them into the database.

This works fine, but if the e-mail contains for instance a signature in the bottom the code fails because it's also trying to parse that text.

Therefor I would like to rewrite the below parsing code to stop when it hits an empty line in the e-mail. All the price data is always at the top of the e-mail.

email_text = params[:plain]
email_text_array = []

email_text.split("\n").each do |email_line|
    email_text_array << email_line.split(" ")
end 

How do I change the above to stop when it hits an empty line in the email_taxt variable?

Thanks!


Solution

  • You can add a break :

    email_text.split("\n").each do |email_line|
      break if email_line.blank?  # ends loop on first empty line
      email_text_array << email_line.split(" ")
    end