JaimeRave JaimeRave - 4 months ago 10
Ruby Question

Escape forward slash in ruby

I'm trying to escape forward slashes from an URL like this

"http://example.com/qb-xhtml-v1.xsd" => "http:\/\/example.com\/qb-xhtml-v1.xsd"


But when I try with gsub, this is what I'm getting

"http://example.com/qb-xhtml-v1.xsd".gsub("/", '\/')
=> "http:\\/\\/example.com\\/qb-xhtml-v1.xsd"


I also tried with

"http://example.com/qb-xhtml-v1.xsd".gsub("/", '/' => '\/')


and

"http://example.com/qb-xhtml-v1.xsd".gsub(/[\/]/, '\/')


with the same result. Any ideas?

Answer

I believe that the interactive ruby shell you're using is adding extra backslashes that aren't really there.

I tried your code in irb and got the same result:

irb(main):005:0> "http://example.com/qb-xhtml-v1.xsd".gsub("/", '\/')
"http:\\/\\/example.com\\/qb-xhtml-v1.xsd"

But if I use puts() it prints correctly:

irb(main):006:0> puts "http://example.com/qb-xhtml-v1.xsd".gsub('/', '\/')
http:\/\/example.com\/qb-xhtml-v1.xsd
=> nil

I suspect that the ruby shell is simply escaping the backslashes for convenience, which is causing confusion.