From: Brian Candler Date: 2009-05-12T05:25:56+09:00 Subject: Re: question to write \4 into file Cheyne Li wrote: > Hi there, > > I have problem with writng "\4" into a file, for example, I want to > write a string "aaa\4024_folder\mm" into a file test.cfg. But once the > string wrote into file, it is "aaa024_folder\mm". That's because \4 inside a double-quoted string is a single character, with code 4. If you want a backslash inside a double-quoted string, put two backslashes. irb(main):001:0> str = "aaa\\4024_folder\\mm" => "aaa\\4024_folder\\mm" irb(main):002:0> puts str aaa\4024_folder\mm => nil If you are building filenames, note that even under Windows you can use forward-slashes inside Ruby. Inside a gsub replacement string it can be even more confusing, since a backslash followed by 4 means "replace this with the fourth capture in the match". So to replace x with \4, you need to do this irb(main):003:0> str = "wxyz" => "wxyz" irb(main):004:0> res = str.gsub(/x/, "\\\\4") => "w\\4yz" irb(main):005:0> puts res w\4yz => nil Or use the block form of gsub, which doesn't treat backslash-N specially. irb(main):007:0> res = str.gsub(/x/) { "\\4" } => "w\\4yz" irb(main):008:0> puts res w\4yz => nil -- Posted via http://www.ruby-forum.com/.