Paul
Paul

Reputation: 26640

Non-regexp version of gsub in Ruby

I am looking for a version of gsub which doesn't try to interpret its input as regular expressions and uses normal C-like escaped strings.

Update

The question was initiated by a strange behavior:

text.gsub("pattern", "\\\\\\")

and

text.gsub("pattern", "\\\\\\\\")

are treated as the same, and

text.gsub("pattern", "\\\\")

is treated as single backslash.

Upvotes: 0

Views: 233

Answers (2)

Paul
Paul

Reputation: 26640

There are two layers of escaping for the second parameter of gsub:

The first layer is Ruby string constant. If it is written like \\\\\\ it is unescaped by Ruby like \\\

the second layer is gsub itself: \\\ is treated like \\ + \

double backslash is resolved into single: \\ => \ and the single trailing backslash at the end is resolved as itself.

8 backslashes are parsed in the similar way:

"\\\\\\\\" => "\\\\"

and then

"\\\\" => "\\"

so the constants consisting of six and eight backslashes are resolved into two backslashes.

To make life a bit easier, a block may be used in gsub function. String constants in a block are passed only through Ruby layer (thanks to @Sorrow).

"foo\\bar".gsub("\\") {"\\\\"}

Upvotes: 3

Miki
Miki

Reputation: 7188

gsub accepts strings as first parameter:

the pattern is typically a Regexp; if given as
a String, any regular expression metacharacters
it contains will be interpreted literally

Example:

"hello world, i am thy code".gsub("o", "-foo-")
=> "hell-foo- w-foo-rld, i am thy c-foo-de"

Upvotes: 2

Related Questions