如何在 Ruby 中安全且可逆地转义字符串引号?

Fri*_*dFX 5 ruby string encoding

Python 字符串encode('string_escape')decode函数的 Ruby 等价物是什么?

在Python中,我可以执行以下操作:

>>> s="this isn't a \"very\" good example!"
>>> print s
this isn't a "very" good example!
>>> s
'this isn\'t a "very" good example!'
>>> e=s.encode('string_escape')
>>> print e
this isn\'t a "very" good example!
>>> e
'this isn\\\'t a "very" good example!'
>>> d=e.decode('string_escape')
>>> print d
this isn't a "very" good example!
>>> d
'this isn\'t a "very" good example!'
Run Code Online (Sandbox Code Playgroud)

如何在 Ruby 中做同样的事情?

byt*_*101 1

大概inspect

\n\n
irb(main):001:0> s="this isn\'t a \\"very\\" good example!"\n=> "this isn\'t a \\"very\\" good example!"\nirb(main):002:0> puts s\nthis isn\'t a "very" good example!\n=> nil\nirb(main):003:0> puts s.inspect\n"this isn\'t a \\"very\\" good example!"\n
Run Code Online (Sandbox Code Playgroud)\n\n

请注意,解码要棘手得多,因为检查还会转义 utf-8 文件中无效的任何内容(例如二进制文件),因此,如果您知道除了有限子集之外将永远不会有任何内容,请使用 gsub,但是,这是唯一真正的方法将其转回字符串正在解析它,无论是从您自己的解析器还是eval

\n\n
irb(main):001:0> s = "\\" hello\\xff I have\\n\\r\\t\\v lots of escapes!\'"\n=> "\\" hello\\xFF I have\\n\\r\\t\\v lots of escapes!\'"\nirb(main):002:0> puts s\n" hello\xef\xbf\xbd I have\n\n         lots of escapes!\'\n=> nil\nirb(main):003:0> puts s.inspect\n"\\" hello\\xFF I have\\n\\r\\t\\v lots of escapes!\'"\n=> nil\nirb(main):004:0> puts eval(s.inspect)\n" hello\xef\xbf\xbd I have\n\n         lots of escapes!\'\n=> nil\n
Run Code Online (Sandbox Code Playgroud)\n\n

显然,如果您不是执行该操作的人inspect,则不要使用 eval,编写自己的/找到一个解析器,但是如果您是inspect之前调用的人eval并且 s 保证是一个字符串(s.is_a? String) ,那么它是完全安全的

\n

  • `eval` 绝对不是你想要的东西。 (2认同)