JaimeRave JaimeRave - 1 year ago 79
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("/", '/' => '\/')


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

with the same result. Any ideas?

Answer Source

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("/", '\/')

But if I use puts() it prints correctly:

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download