ruby write newline character to file but do not interpret as a true newline
I am trying to write a ruby s开发者_JAVA技巧tring to a file in such a way that any newline characters embedded in the string remain embedded. This is being written out to a file which will then be processed by another tool.
An example is below.
I want this: 1 [label="this is a\ntest"] \n (second \n is a true newline)
I have tried this: string = '1 [label="this is a\ntest"]' + "\n"
Any thoughts?
I figured it out. I was using rails word_wrap helper function to wrap text and that was using "\n" and not '\n'. I copied the function and wrote my own.
Good to go now.
In Ruby, single quotes don't interpret escape sequences. You could use the quote operator:
string = %Q/1 [label="this is a\\ntest"] \n/
The character after %Q is the string beginning, ending delimiter. ruby intelligently uses paired characters that have open close equivalents. e.g.
string = %Q{1 [label="this is a\\ntest"] \n}
string = %Q(1 [label="this is a\\ntest"] \n)
string = %Q!1 [label="this is a\\ntest"] \n!
This lets you choose a convenient delimiter doesn't need additional escaping for a particular string literal.
the first newline in the example above is read as a real newline by the downstream processing tool.
This sounds like your problem, then. Your processing tool is taking the literal whack-n (aka \x5c\x6e) and translating it to a single \x0a).
In other words, your output process is fine -- it's your input process is unsafe. You can check your string like so:
string.split(//).map {|x| x[0].ord.to_s(16)}
You'll notice there's only one "a" there, at the end.
精彩评论