So, I have
puts "test\\nstring".gsub(/\\n/, "\n")
and that works.
But how do I write one statement that replaces \n, \r, and \t with their correctly escaped counterparts?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Those aren’t escaped characters, those are literal characters that are only represented as being escaped so they’re human readable. What you need to do is this:
You will have to add other escape characters as required, and this still won’t accommodate some of the more obscure ones if you really need to interpret them all. A potentially dangerous but really simple solution is to just eval it:
So long as you can be assured that your input stream doesn’t contain things like
#{ ... }that would allow injecting arbitrary Ruby, which is possible if this is a one shot repair to fix some damaged encoding, this would be fine.Update
There might be a mis-understanding as to what these backslashes are. Here’s an example:
You can see these are two entirely different things.
\nis a representation of ASCII character 10, a linefeed.