How to escape spaces

J

Jonathan Wallace

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
 
R

Reprisal

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
 
M

MonkeeSage

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,262
Messages
2,571,056
Members
48,769
Latest member
Clifft

Latest Threads

Top