Replacing ' with \'

N

Nikita Petrov

In my practice I need to replace apostrophe with backslash and
apostrophe in string. I using String#gsub, but it has unpredictable
result in my own. That's I do in IRB to test my gsub call:

irb(main):001:0> str = "O'Reilly"
=> "O'Reilly"
irb(main):002:0> str.gsub("'", "\\'")
=> "OReillyReilly"

As You see I have magic result: I want to have "O\\'Reilly", but result
is one - "OReillyReilly".

Does anybody known how to fix this problem? Thanks.
 
T

Thomas B.

Nikita said:
In my practice I need to replace apostrophe with backslash and
apostrophe in string. I using String#gsub, but it has unpredictable
result in my own. That's I do in IRB to test my gsub call:

irb(main):001:0> str = "O'Reilly"
=> "O'Reilly"
irb(main):002:0> str.gsub("'", "\\'")
=> "OReillyReilly"

As You see I have magic result: I want to have "O\\'Reilly", but result
is one - "OReillyReilly".

Does anybody known how to fix this problem? Thanks.

The backslash has a special meaning in gsub. Use str.gsub("'", "\\\\'")
instead.

TPR.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,708
Latest member
SherleneF1

Latest Threads

Top