Gediminas Šukys
Gediminas Šukys

Reputation: 7391

Removing line breaks in 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.

Upvotes: 9

Views: 30172

Answers (3)

Wilson Silva
Wilson Silva

Reputation: 11385

If you don't care about extra blank spaces, the cleanest solution is to use #strip:

"Remove \n".strip

Upvotes: 0

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230286

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 "

Upvotes: 22

Zero Fiber
Zero Fiber

Reputation: 4465

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 \\"

Upvotes: 2

Related Questions