在Ruby中避免和解除字符串的最佳方式? [英] Best way to escape and unescape strings in Ruby?
问题描述
到目前为止,我已经提出了这些功能。他们工作,但他们似乎有点黑客:
def escape(s)
s.inspect [1 .. -2]
end
def unescape(s)
eval%Q {#{s}}
end
有更好的方法吗?
如果您不想使用 eval
,但愿意使用 YAML
模块,您可以使用它而是:
require'yaml'
def unescape
YAML.load(%Q(--- \\\
#{s}\\\
))
end
YAML
超过 eval
的优点是,它可能更安全。 cane
不允许所有使用 eval
。我已经看到建议使用 $ SAFE
以及 eval
,但是目前不能通过JRuby使用。 p>
对于什么是值得的,Python确实对 unescaping反斜杠。
Does Ruby have any built-in method for escaping and unescaping strings? In the past, I've used regular expressions; however, it occurs to me that Ruby probably does such conversions internally all the time. Perhaps this functionality is exposed somewhere.
So far I've come up with these functions. They work, but they seem a bit hacky:
def escape(s)
s.inspect[1..-2]
end
def unescape(s)
eval %Q{"#{s}"}
end
Is there a better way?
If you don't want to use eval
, but are willing to use the YAML
module, you can use it instead:
require 'yaml'
def unescape(s)
YAML.load(%Q(---\n"#{s}"\n))
end
The advantage to YAML
over eval
is that it is presumably safer. cane
disallows all usage of eval
. I've seen recommendations to use $SAFE
along with eval
, but that is not available via JRuby currently.
For what it is worth, Python does have native support for unescaping backslashes.
这篇关于在Ruby中避免和解除字符串的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!