1.8.7 :001 > s = "hi\nthere"
=> "hi\nthere"
1.8.7 :002 > p s
"hi\nthere"
Escape line breaks in puts output
-
01-06-2022 - |
문제
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
다른 팁
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.
제휴하지 않습니다 StackOverflow