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?
Please try the following code which works “a b c”.sub(“b”,
‘believe\+me’).
Since this string isn’t hardcoded, I’ll have to write a function to add
these slashes, and all this is becoming ugly: I don’t want to waste time
on debugging.
I finally solved my problem by doing:
“a b c”.sub(“b”) { “believe\+me” }
But I wonder if this is the “best” Ruby has to offer for my very humble
demands.
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”
But I wonder if this is the “best” Ruby has to offer for my very humble
demands.
It’s usually slower. The intended use of the block form is where
calculations need to be done for each replacement. That’s not the
case here. Please see Brian’s excellent explanation of how it’s done
without block and why so many backslashes are needed.
Kind regards
robert
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.