Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

> "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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading