benchwarmer
benchwarmer

Reputation: 2774

How do I insert backslash?

I have string like file name. I want to output like file\ name. I have tried following.

ruby-1.9.2-p290 :060 > s.gsub(/\s/,"\ ")  
 => "file name"   
ruby-1.9.2-p290 :074 > s.gsub(" ","\\")  
 => "file\\name" 

Any help would be great.

Upvotes: 0

Views: 143

Answers (2)

amiuhle
amiuhle

Reputation: 2773

You can also use 'single quoted strings'. They are not escaped in ruby.

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

You probably want

s.gsub(" ","\\ ")
=> "file\\ name"

This is a single backslash character, but its representation needs a double backslash to differentiate it from an actual escape sequence like \n.

Upvotes: 4

Related Questions