在 Ruby 中转义和取消转义字符串的最佳方法? [英] Best way to escape and unescape strings in Ruby?
本文介绍了在 Ruby 中转义和取消转义字符串的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Ruby 是否有任何内置方法来转义 和 非转义字符串?过去,我使用过正则表达式;然而,我突然想到 Ruby 可能一直在内部进行此类转换.也许这个功能在某处公开.
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.
到目前为止,我已经想出了这些功能.他们工作,但他们似乎有点hacky:
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
有更好的方法吗?
推荐答案
Ruby 2.5 添加了 String#undump
作为 String#dump
:
Ruby 2.5 added String#undump
as a complement to String#dump
:
$ irb
irb(main):001:0> dumped_newline = "
".dump
=> ""\n""
irb(main):002:0> undumped_newline = dumped_newline.undump
=> "
"
有了它:
def escape(s)
s.dump[1..-2]
end
def unescape(s)
""#{s}"".undump
end
$irb
irb(main):001:0> escape("
" \")
=> "\n \" \\"
irb(main):002:0> unescape("\n \" \\")
=> "
" \"
这篇关于在 Ruby 中转义和取消转义字符串的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文