How to escape spaces

I’m using ruby 1.8.4. I’m trying to use the gsub function to escape
spaces in a linux path that is stored in a variable.

When I attempt the following, t = “a B”; t.gsub(/ /, "\ "), I receive
the following output:

irb(main):001:0> t = “a B”; t.gsub(/ /, "\ ")
=> “a\ B”

I’d like to get “a\ B” (without quotes, of course). Can someone point
me in the proper direction? Note: I’ve tried many different variations
with no luck.
Thanks,
Jonathan

Jonathan W. wrote:

I’m using ruby 1.8.4. I’m trying to use the gsub function to escape
spaces in a linux path that is stored in a variable.

See
http://www.archivum.info/comp.lang.ruby/2005-09/msg03460.html
or
http://wiki.rubygarden.org/Ruby/page/show/RegexpCookbook

Your trouble isn’t with your gsub patterns I don’t believe but with
what you are seeing in irb.

irb(main):107:0> t=“a B”
=> “a B”
irb(main):108:0> t.gsub(/ /,"\")
=> “a\B”
irb(main):109:0> puts t.gsub(/ /,"\")
a\B
=> nil
irb(main):110:0> 92.chr
=> “\”
irb(main):111:0> puts 92.chr

=> nil
irb(main):112:0> Regexp::escape(t)
=> “a\ B”
irb(main):113:0> puts Regexp::escape(t)
a\ B
=> nil

The representation of a backslash () is an escaped backslash (\);
when the later is evaluated by the interpreter (i.e., you ask for its
value) you get the former. You can check the length of the string, or
just print it out, to see this:

s=‘a\b’ # => “a\b”
s.length # => 3
puts s # => a\b

Regards,
Jordan

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs