Why can't I substitute a single backslash in a string?
a = "\\6"
p a # => "\\6"
puts a # => \6
p a.sub('\', '')
Expected: "\6"
Got:
j:4: unterminated string meets end of file
j:4: parse error, unexpected $, expecting ')'
If I change the replacement to 'c', I get a new error:
j:4: parse error, unexpected tIDENTIFIER, expecting ')'
puts a.sub('\', 'c')
^
j:4: unterminated string meets end of file
Both substitution work fine when the pattern is a regular character.
The substitution also works if num('\') is a multiple of 2, example:
a = '\\6'
p a # => "\\6"
puts a # => \6
p a.sub('\\', '')
I was thinking that it might work by making two passes looking for and
converting backslashes, like this:
(7):
first pass : (\\)(\\)(\\)(\4)
\ \ \ \4
second pass: (\\)(\\)4
result : \\4
But I'm not 100% sure, do you know how it works?
Thanks again.
···
On 6/6/07, james.d.masters@gmail.com <james.d.masters@gmail.com> wrote:
On Jun 6, 2:59 pm, "Federico Zagarzazú" <fzagarz...@gmail.com> wrote:
> Why can't I substitute a single backslash in a string?
> a = "\\6"
> ...
> p a.sub('\', '')
Because you're essentially escaping a single quote in your String#sub
method call. Double escape that too:
You have to be careful with using backslashes with a number for a
replacement string. In a replacement string, \# (where # is a number)
indicates that you want to insert something that was matched in the
original string - the matched things are in parentheses and occur in
regular expressions. For example:
irb(main):001:0> a = "Page 3 of 86"
=> "Page 3 of 86"
irb(main):002:0> a.sub(/^Page (\d+) of (\d+)$/, 'You are on page \1
out of a total of \2 pages')
=> "You are on page 3 out of a total of 86 pages"
The PickAxe has an excellent subject on this and goes over your
question with all sorts of backslash permutations. I guarantee that
it will clarify things further for you:
"Within single-quoted strings, two consecutive backslashes are replaced
by a single backslash, and a backslash followed by a single quote
becomes a single quote. Double-quoted strings support a boatload more
escape sequences."
You have to be careful with using backslashes with a number for a
replacement string. In a replacement string, \# (where # is a number)
indicates that you want to insert something that was matched in the
original string - the matched things are in parentheses and occur in
regular expressions. For example:
irb(main):001:0> a = "Page 3 of 86"
=> "Page 3 of 86"
irb(main):002:0> a.sub(/^Page (\d+) of (\d+)$/, 'You are on page \1
out of a total of \2 pages')
=> "You are on page 3 out of a total of 86 pages"
The PickAxe has an excellent subject on this and goes over your
question with all sorts of backslash permutations. I guarantee that
it will clarify things further for you: