在Ruby中避免和解除字符串的最佳方式? [英] Best way to escape and unescape strings in Ruby?

查看:104
本文介绍了在Ruby中避免和解除字符串的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby是否有任何内置方法来转义转义字符串?过去,我使用正则表达式;然而,对我来说,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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆