regexrubygsub

String#gsub how to use a match occurrence in the replace attribute and also insert a break line


With String#gsub I can insert break lines in the replace attribute:

"my string".gsub(/\s/, "\n") #=> "my\nstring"

But if I also what to use part of the regex match in the replace attribute I am forced to use single quotas ('). And then I don't know how to also insert a break line.

I have tried:

> "my string".gsub!(/(my )/, '\1\n')
=> "my \\nstring"
> "my string".gsub!(/(my )/, '\1\\n')
=> "my \\nstring"
> "my string".gsub!(/(my )/, '\1\\\n')
=> "my \\nstring"
> "my string".gsub!(/(my )/, '\1\\\\n')
=> "my \\nstring"
> "my string".gsub!(/(my )/, '\1\\\\\n')
=> "my \\\\nstring"
> "my string".gsub!(/(my )/, '\1\\\\\n')
=> "my \\\\nstring"

Nothing works.


Solution

  • You don't need to use single quotes. Just use double quotes and escape \1 to \\1:

    irb> "my string".gsub(/(my )/, "\\1\n")
    => "my \nstring"
    

    The difference between single and double quotes is that in single quoted strings, you cannot use escape sequences (other than for single quotes). These strings are equivalent:

    irb> '\1' == "\\1"
    => true
    irb> '\n' == "\\n"
    => true