4

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!'

如何在 Ruby 中做等价物?

4

3 回答 3

1

好吧,你可以这样做:

'string"and"something'.gsub '"', '\"'
于 2013-11-15T01:31:53.557 回答
0

大概inspect

irb(main):001:0> s="this isn't a \"very\" good example!"
=> "this isn't a \"very\" good example!"
irb(main):002:0> puts s
this isn't a "very" good example!
=> nil
irb(main):003:0> puts s.inspect
"this isn't a \"very\" good example!"

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

irb(main):001:0> s = "\" hello\xff I have\n\r\t\v lots of escapes!'"
=> "\" hello\xFF I have\n\r\t\v lots of escapes!'"
irb(main):002:0> puts s
" hello� I have

         lots of escapes!'
=> nil
irb(main):003:0> puts s.inspect
"\" hello\xFF I have\n\r\t\v lots of escapes!'"
=> nil
irb(main):004:0> puts eval(s.inspect)
" hello� I have

         lots of escapes!'
=> nil

显然,如果你不是那个在做的人inspect,那么不要使用 eval,编写你自己的/找到一个解析器,但是如果你是inspect之前调用的那个eval并且 s 保证是一个字符串(s.is_a? String

于 2013-11-14T23:55:26.143 回答
0

我不知道这是否相关,但如果我想避免处理转义,我只需使用%q[ ]语法

s = %q[this isn't a "very" good example!]
puts s
p s

会给

'this isn't \ a "very" good example!'
"'this isn't \\ a \"very\" good example!'"
于 2013-11-15T00:13:59.647 回答