Brian D
Brian D

Reputation: 963

Inserting newlines (\n) into gsub replace arguments

I tried to insert newlines into a gsub replacement pattern. It works if the replacement is double quoted string literal like "text\ntext", but not if the replacement is a variable. This may be related to how I refer to my replacement strings.

If I do:

replace = "\n// some text"
text.gsub!(/#{find}/, replace)

it works just fine.

But when the replacement string that contains \n is written in a file,

\n// some text

read via File.open, and is stored as a string, then the replacements:

text.gsub!(/#{find}/, "#{replace}")
text.gsub!(/#{find}/, replace)

insert literal \n characters.

Upvotes: 0

Views: 1410

Answers (1)

Linuxios
Linuxios

Reputation: 35823

\n is the escape code for newline. \ escapes only work in literal strings included in Ruby source files. When read in from outside sources, \n is just the literal characters \ and n.

An easy fix, if you want to be able to specify newlines using \n in your input file, is to add

replace = replace.gsub('\n', "\n")

Before you use replace. This replaces literal \n's in replace with actual newlines.

Upvotes: 2

Related Questions