Rafael V. wrote:
But when I do:
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.
- First, there’s what IRB is showing you when you make an entry vs.
it’s actually going to provide when queried.
irb(main):001:0> var = ‘\foo’
irb(main):002:0> puts var
irb(main):003:0> puts var.length
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
escape character. You can see that when you do the puts. You can also
it in the length of the string.
- Second, there’s the difference in how Ruby treats single vs double
irb(main):004:0> var = “\foo”
irb(main):005:0> puts var
irb(main):006:0> puts var.length
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
the part of what you say you’re seeing that I can’t reproduce. On
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”
irb(main):008:0> puts var
irb(main):009:0> puts var.length