Tuesday, April 3, 2012

Using Ruby to create linebreaks in Windows

I am creating a file generator for taking data in a cucumber test and dumping into into a proprietary pipe "|" delimited file format for upload into our system.  I plan on posting about that process later, but I wanted to highlight something I found a bit frustrating to understand.  This has nothing really to do with Cucumber or Watir.  It's a very basic Ruby thing, but I spent a while looking around for an answer.

I was having trouble getting newlines to work.  Most of my trouble ended up being with white space not being trimmed from a value I was comparing.  But after I resolved that issue (rather inelegantly, but that's another discussion), I still couldn't get it to work.  I was passing '\n', '\r\n', '\n\r', and finally I tried something.  I passed "\n".  It worked like a charm.  In the back of my mind was this nagging feeling.  Don't single and double quote characters work differently?  Yes they do.  Single quote strings output everything literally.  If you want to use escape characters such as \n, you need to use double quotes.

You can find more information here:  http://www.rubyist.net/~slagell/ruby/strings.html

It's important to know, this just works on Windows.  You don't need to pass a carriage return \r as well.  That will be added for you  Now, if you're outputting files that need to be used on a Linux box or Mac, you'll need to do something a little different.  You need to open the file for writing as Binary.  There's a good discussion of this on Stack Overflow: http://stackoverflow.com/questions/8064175/writing-unix-line-breaks-on-windows-with-jruby

File.open(filename, 'wb') do |file|
  file.print "My text\n"
end

No comments:

Post a Comment