Gsub causing part string replacement

I want to replace all occurrences of a single quote ( ') with a single backslash quote ( \'). I tried to do this with gsub, but I get a partial duplication of strings:

a = "abc 'def' ghi"
a.gsub("'", "\\'")
# => "abc def' ghidef ghi ghi"

Can someone explain why this is happening and what is the solution for this?

+4
source share
3 answers

This is because it "\\'"is of particular importance when it occurs as an argument for substitution gsub, namely, it means a substring after the match.

To do what you want, you can use a block:

a.gsub("'"){"\\'"}
# => "abc \\'def\\' ghi"

, , \\.

+3

"\\'" \' - , . \' Ruby regex , , . , .

abc 'def' ghi
    ^

, '. , .. def' ghi.

abc def' ghidef' ghi
    ++++++++

:

abc def' ghidef' ghi
               ^

' , .. ghi.

abc def' ghidef ghi ghi
               ++++
+3

, :

a.gsub(/'/, "\\\\'" )

abc\'def \' ghi

+2

Source: https://habr.com/ru/post/1625430/


All Articles