From: Bill Walton Date: 2008-09-08T23:08:24+09:00 Subject: Re: Single backslash in a string. How?? Hi Rafael, Rafael Viana wrote: > Is it possible to have a string with a single backslash? > > I want var to have the value "\foo" > > And when I do something like: > > var = "\foo" > I get > "foo" > > But when I do: > > var = "\\foo" > I get > "\\foo" > > And when I do: > > var = '\foo' > I get > "\\foo" > > I even tried to remove one of the backslashes from the "\\foo" string, > but then I just get "foo" :-( I can't reproduce your results exactly, but I think I can explain what you're seeing. It's a combination of things. 1) First, there's what IRB is showing you when you make an entry vs. what it's actually going to provide when queried. irb(main):001:0> var = '\foo' => "\\foo" irb(main):002:0> puts var \foo => nil irb(main):003:0> puts var.length 4 => nil The feedback at 0001:0 above is telling you that Ruby is storing the backslash character you entered as an actual character vs. treating it as an escape character. You can see that when you do the puts. You can also see it in the length of the string. 2) Second, there's the difference in how Ruby treats single vs double quotes. irb(main):004:0> var = "\foo" => "\foo" irb(main):005:0> puts var ♀oo => nil irb(main):006:0> puts var.length 3 => nil Double quotes tell Ruby to try to interpret what's inside. In this case it's interpreting the first two characters as an escape sequence. This is the part of what you say you're seeing that I can't reproduce. On Windows, at 005:0 I get the above. On Linux I get a non-displayable character rendered. In both cases the var.length is 3. You can use double quotes, but you have to explicitly tell Ruby that the backslash doesn't signal an escape sequence by escaping it. irb(main):007:0> var = "\\foo" => "\\foo" irb(main):008:0> puts var \foo => nil irb(main):009:0> puts var.length 4 HTH, Bill