Replacing ' with \'

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.

···

--
Posted via http://www.ruby-forum.com/.

Nikita Petrov wrote:

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.

···

--
Posted via http://www.ruby-forum.com/\.

Thomas B. wrote:

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

Thanks, that helped me.

···

--
Posted via http://www.ruby-forum.com/\.