5

I have a string containing an escape character:

word = "x\nz"

and I would like to print it as x\nz.

However, puts word gives me:

x
z

How do I get puts word to output x\nz instead of creating a new line?

2 Answers 2

10

Use String#inspect

puts word.inspect #=> "x\nz"

Or just p

p word #=> "x\nz"
Sign up to request clarification or add additional context in comments.

Comments

1

I have a string containing an escape character:

No, you don't. You have a string containing a newline.

How do I get puts word to output x\nz instead of creating a new line?

The easiest way would be to just create the string in the format you want in the first place:

word = 'x\nz'
# or 
word = "x\\nz"

If that isn't possible, you can translate the string the way you want:

word = word.gsub("\n", '\n')
# or
word.gsub!("\n", '\n')

You may be tempted to do something like

puts word.inspect
# or
p word

Don't do that! #inspect is not guaranteed to have any particular format. The only requirement it has, is that it should return a human-readable string representation that is suitable for debugging. You should never rely on the content of #inspect, the only thing you should rely on, is that it is human readable.

1 Comment

What exactly is wrong with using #inspect? The docs say "Returns a printable version of str, surrounded by quote marks, with special characters escaped.". This sounds like exactly what the OP wants, and sounds like a perfectly reasonable definition of a 'format'. Can you clarify your objection?

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.