I have a problem removing \n
and \r
tags. When I'm using double quotes, it works fine, otherwise it leaves "\"
. With gsub
, it doesn't work without double quotes at all. Why?
"Remove \n".delete('\n') # result: "Remove"
'Remove \n'.delete('\n') # result: "Remove \"
I found this because it doesn't work with results from the database.
Single-quoted strings do not process most escape sequences. So, when you have this
'\n'
it literally means "two character string, where first character is backslash and second character is lower-case 'n'". It does not mean "newline character". In order for \n
to mean newline char, you have to put it inside of double-quoted string (which does process this escape sequence). Here are a few examples:
"Remove \n".delete('\n') # => "Remove \n" # doesn't match
'Remove \n'.delete('\n') # => "Remove \\" # see below
'Remove \n'.delete("\n") # => "Remove \\n" # no newline in source string
"Remove \n".delete("\n") # => "Remove " # properly removed
NOTE that backslash character in this particular example (second line, using single-quoted string in delete
call) is simply ignored, because of special logic in the delete
method. See doc on String#count for more info. To bypass this, use gsub
, for example
'Remove \n'.gsub('\n', '') # => "Remove "
From Ruby Programming/Strings
Single quotes only support two escape sequences.
\' – single quote \\ – single backslash
Except for these two escape sequences, everything else between single quotes is treated literally.
So if you type \n
in the irb, you get back \\n
.
This is why you have problems with delete
"Remove \n".delete('\n') #=> "Remove \n".delete("\\n") => "Remove \n"
'Remove \n'.delete('\n') #=> "Remove \\n".delete("\\n") => "Remove \\"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With