Replacing ' with \' using gsub

I tried to replace “’” characters with “’” strings using gsub. What
happened instead was something completely different. Am I missing
something here?
(in irb)
irb(main):001:0> s = “a’b’”
=> “a’b’”
Unexpected result
irb(main):002:0> s.gsub(/’/, “\’”)
=> “ab’b”
Also with this
irb(main):003:0> s.gsub(/’/, ‘\’’)
=> “ab’b”
However this works
irb(main):004:0> s.gsub(/’/, “\x’”)
=> “a\x’b\x’”

Thank you for your help!
-js

Seems to me like a bug in the regex code.
using ruby 1.8.4 (2005-12-24) [i386-mswin32]

J.

Jan S. wrote:

Seems to me like a bug in the regex code.
using ruby 1.8.4 (2005-12-24) [i386-mswin32]

But it isn’t. You need more backslashes.

See "Explanation for the multitude of backslashes " at
http://wiki.rubygarden.org/Ruby/page/show/RegexpCookbook
or search the list archives, as this comes up frequently by newcomers
(including myself, when I was young ;).

irb(main):001:0> s = “a’b’”
=> “a’b’”
irb(main):002:0> s.gsub(/’/, “\’”)
=> “ab’b”
irb(main):003:0> s.gsub(/’/, “\\’”)
=> “a\‘b\’”

Regards, Morton

“J” == Jani S. [email protected] writes:

J> irb(main):001:0> s = “a’b’”
J> => “a’b’”
J> Unexpected result
J> irb(main):002:0> s.gsub(/’/, “\’”)
J> => “ab’b”

“\’” is the same than $’, i.e. MatchData#post_match. For example

irb(main):001:0> s = “a’b’”
=> “a’b’”
irb(main):002:0> s.match(/’/).post_match
=> “b’”
irb(main):003:0>

ruby replace the first <’> with <b’>
the second <’> with <> (there is nothing after the last ')

Guy Decoux

On 7/21/06, ts [email protected] wrote:

“\’” is the same than $’, i.e. MatchData#post_match. For example

Now that makes more sense… I didn’t know that. After looking in the
documentation, I found this only in PickAxe book. I haven’t found it
neither in the 1.8 RDoc nor in the mentioned article.

Attached is a patch against 1.182.2.48 revision of string.c, that adds
these sequences to rdoc (shamelessly ripped from the pickaxe book).

J.

On Jul 21, 2006, at 1:30 PM, ts wrote:

irb(main):001:0> s = “a’b’”
Guy Decoux

What he said.

Also if you don’t want to drive yourself crazy with fifteen billion
backslahes:

str.gsub(/’/) { %q{’} }