Gsub and "\\"

Hi,

I’m a bit confused on how to use gsub when the string I want
to substitute for can contain “\” and “?” etc.

Examples:

“a”.gsub(“a”, “\8”) => “” (but I want “\8”)

so I thought maybe I can use Regexp.escape

“a”.gsub(“a”, Regexp.escape("\8")) => “\8” (great!)

but now if there is a question mark it won’t work

“a”.gsub(“a”, Regexp.escape("\8?")) => “\8\?” but I want
it to be “\8?”

I guess there is a simple solution but I can’t see it right
now. Any help appreciated!

Regards,

Karsten Magnuauer

···


http://fastmail.fm - Same, same, but different…

Hello,

“a”.gsub(“a”,“\\8?”) >> “\8?”

hth,
Alia

coma_killen@fastmail.fm wrote:

···

Hi,

I’m a bit confused on how to use gsub when the string I want
to substitute for can contain “\” and “?” etc.

Examples:

“a”.gsub(“a”, “\8”) => “” (but I want “\8”)

so I thought maybe I can use Regexp.escape

“a”.gsub(“a”, Regexp.escape(“\8”)) => “\8” (great!)

but now if there is a question mark it won’t work

“a”.gsub(“a”, Regexp.escape(“\8?”)) => “\8\?” but I want
it to be “\8?”

I guess there is a simple solution but I can’t see it right
now. Any help appreciated!

Regards,

Karsten Magnuauer


http://fastmail.fm - Same, same, but different…

coma_killen@fastmail.fm wrote:

Hi,

I’m a bit confused on how to use gsub when the string I want
to substitute for can contain “\” and “?” etc.

Hi,

There are some examples on how deal with ‘\’ (but not ‘?’) in Item 20 in
“Things That Newcomers to Ruby Should Know”:

http://www.glue.umd.edu/~billtj/ruby.html#backslashes

Regards,

Bill