NowNick
NowNick

Reputation: 304

Escape whitespace characters in Ruby

I have a string:

"hello\n\nsomeletters\t\nmoreletters\n"

What I want:

"hello\\n\\nsomeletters\\t\\nmoreletters\\n"

How to do it?

I know a gsub way. But it sounds very simple and seems to be a common problem therefore I am sure that Ruby Gods have already sent us a solution.

Upvotes: 0

Views: 757

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

There are different possibilities. The closest to what you want would be Regexp#escape:

Regexp.escape "hello\n\nsomeletters\t\nmoreletters\n"
#⇒ "hello\\n\\nsomeletters\\t\\nmoreletters\\n"

But be aware it will escape some other symbols having a special meaning in regular expressions.

Also, we have Shellwords#escape, which is probably not what you want here.

For escaping backslashes only there is no dedicated method because this operation basically has a little sense and it is not worth it to call it instead of:

"hello\n\nsomeletters\t\nmoreletters\n".gsub(
    /\n|\t/, {"\n" => "\\n", "\t" => "\\t"}
)

Please note, there are no slash characters in the initial string, hence you are to match all the expected sequences.

Upvotes: 1

Related Questions