Вопрос

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!"
Это было полезно?

Решение 2

1.8.7 :001 > s = "hi\nthere"
 => "hi\nthere" 
1.8.7 :002 > p s
"hi\nthere"

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top