in Hacking

Ruby gsub gotcha

Today I struggled with a string replace that didn't do what I expected it to do.

Consider the following code:

"xyz".gsub("y","a\\'b")
=> "xazbz"

Because gsub can be used with a regular expression the replace value can use regular expression backrefs.

I assumed (assumption is the mother of all fuckups) when using a plain string as search term, (which cannot result in back refs) it didn't use backrefs..
Well I was wrong..

A solution is to use the block-variant:

"xyz".gsub("y") { "a\\'b" }
=> "xa\\'bz"

I think the behavior of gsub is wrong...
When you don't have a regular expression you cannot have backrefs and you can have a dumb string replace.... What's your opinion about this?

  • Related Content by Tag