4

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?

Stefan
  • 109,145
  • 14
  • 143
  • 218
user9325554
  • 43
  • 1
  • 3

2 Answers2

9

Use String#inspect

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

Or just p

p word #=> "x\nz"
Sagar Pandya
  • 9,323
  • 2
  • 24
  • 35
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.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • 1
    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? – preferred_anon Dec 04 '18 at 12:22