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