Reputation: 5131
I am using a Ruby script to process some text files. Basically, reading each line, sometimes doing some manipulation and then writing the line to an output text file.
This works well, except when the original line has a new line \n
character in there. In this case, the script will "execute" the new line instead of copying it literally.
edit
# output code:
modified_line # => "hello\nworld"
output.write(modified_line) # will output
hello
world
# output I am looking for:
hello\nworld
How can I make Ruby just write the string variable verbatim, ignoring any included special chars?
Upvotes: 0
Views: 1329
Reputation: 2520
Assuming you do some file.write(string_variable)
.
Use would want to use String#dump which escapes all special characters. Like it says in the documentation:
Produces a version of str with all nonprinting characters replaced by \nnn notation and all special characters escaped.
So your code would look like
file.write(string_variable.dump)
Upvotes: 1