Ruby - How to keep \n when I print out strings
i would suggest to use p
instead of puts
/print
:
p "abc\nabc"
=> "abc\nabc"
and in fact with pry
you do not need to use any of them, just type your string and enter:
str = "abc\nabc"
=> "abc\nabc"
str
=> "abc\nabc"
Because \n is a special keyword, you have to escape it, by adding a backslash before the special keyword (and because of that, backslashes must also be escaped), like so: abs\\nabc
. If you wanted to print \\n
, you would have to replace it to be abs\\\\n
, and so on (two backslashes to display a backslash).
You can also just use single quotes instead of double quotes so that special keywords will not be interpreted. This, IMHO, is bad practice, but if it makes your code look nicer, I guess it's worth it :)
Here are some examples of ways you can escape (sort of like a TL;DR version):
puts 'abc\nabc' # Single quotes ignore special keywords
puts "abc\\nabc" # Escaping a special keyword (preferred technique, IMHO)
p "abc\nabc" # The "p" command does not interpret special keywords
In Ruby, strings in a single quote literal, like 'abc\nabc' will not be interpolated.
1.9.3p194 :001 > print 'abc\nabc'
abc\nabc => nil
vs with double quotes
1.9.3p194 :002 > print "abc\nabc"
abc
abc => nil