Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing line breaks in Ruby

Tags:

ruby

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.

like image 577
Gediminas Avatar asked Jun 16 '13 10:06

Gediminas


2 Answers

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 "
like image 105
Sergio Tulentsev Avatar answered Sep 21 '22 20:09

Sergio Tulentsev


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 \\"
like image 37
Zero Fiber Avatar answered Sep 19 '22 20:09

Zero Fiber