Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape line breaks in puts output

In IRB on Ruby 1.8.7, I have a collection of strings I'm working with that have newlines in them. When these newlines are output, I want to explicitly see the \r and \n characters within my strings. Is there some way to tell puts to escape those characters, or a method similar to puts that will do what I want?

Note that directly evaluating each string isn't satisfactory because I want to be able to do something like this:

=> mystrings.each { |str| puts str.magical_method_to_escape_special_chars }
This is\na string in mystrings.
This is another\n\rstring.

And don't want to have to do this:

=> mystrings[0]
"This is\na string in mystrings."
=> mystrings[1]
"This is another\n\rstring."
...
=> mystrings[1000]
"There are a lot of\n\nstrings!"
like image 462
Kevin Avatar asked Oct 27 '25 09:10

Kevin


1 Answers

I can use the string#dump method:

=> mystrings.each { |str| puts str.dump }
This is\na string in mystrings.
This is another\n\rstring.

According to the Ruby documention for String, string#dump

Produces a version of str with all nonprinting characters replaced by \nnn notation and all special characters escaped.

like image 129
Kevin Avatar answered Oct 30 '25 12:10

Kevin