tags:

views:

103

answers:

1

I am retrieving emails using the Fetcher plugin for Rails. It is doing a fine job. But I am trying to split the body of the email on newlines but it appears that it is only one really long line.

What is the best way (in Ruby) to split an email up into multiple lines?

+2  A: 

Sounds like you need a word wrapping algorithm. Here is a short and clever way of word wrapping in Ruby that I found on the ruby-talk mailing list (link is to Google's cache because the site seems to be down):

puts $<.read.gsub(/\t/,"     ").gsub(/.{1,50}(?:\s|\Z)/){($& + 
5.chr).gsub(/\n\005/,"\n").gsub(/\005/,"\n")}

Here's a slightly prettier version wrapped in a method:

def wordwrap(str, columns=80)
  str.gsub(/\t/, "     ").gsub(/.{1,#{ columns }}(?:\s|\Z)/) do
    ($& + 5.chr).gsub(/\n\005/, "\n").gsub(/\005/, "\n")
  end
end
yjerem
That didn't fix it :-(
Sixty4Bit
Does email send it as one long string without newlines and carriage returns? And if so, why does it not appear as one line in the console (which I have set at 120 characters)?
Sixty4Bit
email may or may not have newlines in it. consoles automatically wrap long lines.
davr
Yeah, but do they wrap them correctly? Or just when they hit the edge?
Sixty4Bit
It was 2am, I was splitting with '\n' instead of /\n/ DumbMe.
Sixty4Bit