Substituting apostrphe's

irb(main):003:0> a = “a”
=> “a”
irb(main):004:0> a.gsub(/a/, ‘'’)
=> “'”
irb(main):007:0> a = “abc”
=> “abc”
irb(main):008:0> a.gsub(/a/, ‘\'’)

Did it again… The last line gives “bcbc” as result.

I had a wanted to replace a single apostrophe with an backslash+apostrophe.
E.g. “don’t” => “don\'t” (where \ is a single backslash in a string).

My initial attempt gave strange results …

a = “don’t”
a.sub(/‘/, "\’") # => “dontt”

Backslash-apostrophe is a special replacement pattern that represents the
part of the string following the match, in this case the letter ‘t’.

It took four backslashes to get it to work.

a.sub(/‘/, "\\’") # => “don\'t”

I’m embarassed to say how long it took me to figure that out.

···

From: Peter [mailto:Peter.Vanbroekhoven@cs.kuleuven.ac.be]


– Jim Weirich / Compuware
– FWP Capture Services
– Phone: 859-386-8855