Albert Schlef wrote in post #1069361:
> I'm executing the following code:
>
>  "a b c".sub("b", "believe\\+me")
>
> And I get "a believeme c" in return. That's bad: Where have the two
> characters, "\\+", gone?
>
> I suspect it has to do with the RegExp replacement patterns \1 and so
> on: since \+ isn't valid, it's removed. I thought sub() would notice
> that "b" isn't a regexp and won't trip me on this nonsense.
>
> So, what's the correct way to replace plain strings in Ruby?

In a replacement string, a raw backslash needs to be escaped with 
another backslash.

>> "a b c".sub("b", "believe\\\\+me")
=> "a believe\\+me c"

Note that "\\" is actually a single backslash, and "\\\\" is two 
backslashes, because backslashes within string literals also need to be 
escaped.

>> "\\".size
=> 1
>> "\\\\".size
=> 2

And as you've already found, using the block form doesn't have this 
problem:

>> "a b c".sub("b") { "believe\\+me" }
=> "a believe\\+me c"

-- 
Posted via http://www.ruby-forum.com/.