user9325554
user9325554

Reputation: 43

How to print an escape character in Ruby?

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?

Upvotes: 4

Views: 3593

Answers (2)

Jörg W Mittag
Jörg W Mittag

Reputation: 369438

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.

Upvotes: 1

Sagar Pandya
Sagar Pandya

Reputation: 9497

Use String#inspect

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

Or just p

p word #=> "x\nz"

Upvotes: 9

Related Questions