4

I want to print escaped or raw version of a string. For example: given this string:

"a,
b,
c,
d"

I want to get

"a,\nb,\nc,\nd".

Is it possible?

1
  • 2
    Your question is not clear, in part because it's only newlines that you escape in your example. Please define what you mean by "escaped or raw version of a string". Aside: when you give an example (which is generally most helpful), please assign a variable to each of your input objects (e.g., str = "a,...."). That way, readers can refer to those variables in answers and comments without having to define them. Commented Dec 8, 2015 at 6:38

2 Answers 2

9
s = "a,
b,
c,
d"
s.dump
# => "\"a,\\nb,\\nc,\\nd\"" 
s.dump[1...-1]
# => "a,\\nb,\\nc,\\nd" 
Sign up to request clarification or add additional context in comments.

Comments

6
string = 'a,
b,
c,
d'

> p string.inspect
#=> "\"a,\\nb,\\nc,\\nd\""
# "*** expected output ***"
> p string.inspect.delete('\"')
#=> "a,\\nb,\\nc,\\nd"

Demo

1 Comment

I think it's better to slice rather than delete if the string may contain "

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.