Replacing ' with \' using gsub

J

Jani Soila

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
 
J

Jan Svitok

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

J.
 
M

Morton Goldberg

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
 
T

ts

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
 
L

Logan Capaldo

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

What he said.

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

str.gsub(/'/) { %q{\'} }
 

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

Members online

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,705
Latest member
Stefkari24

Latest Threads

Top