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?
When using strings in Ruby, we sometimes need to put the quote we used to define the string inside the string itself. When we do, we can escape the quote character with a backslash \ symbol.
You can use regexes to remove the ANSI escape sequences from a string in Python. Simply substitute the escape sequences with an empty string using re. sub(). The regex you can use for removing ANSI escape sequences is: '(\x9B|\x1B\[)[0-?]
Alternate double quotes The %Q operator (notice the case of Q in %Q ) allows you to create a string literal using double-quoting rules, but without using the double quote as a delimiter. It works much the same as the %q operator.
Ruby 2.5 added String#undump
as a complement to String#dump
:
$ irb irb(main):001:0> dumped_newline = "\n".dump => "\"\\n\"" irb(main):002:0> undumped_newline = dumped_newline.undump => "\n"
With it:
def escape(s) s.dump[1..-2] end def unescape(s) "\"#{s}\"".undump end $irb irb(main):001:0> escape("\n \" \\") => "\\n \\\" \\\\" irb(main):002:0> unescape("\\n \\\" \\\\") => "\n \" \\"
There are a bunch of escaping methods, some of them:
# Regexp escapings >> Regexp.escape('\*?{}.') => \\\*\?\{\}\. >> URI.escape("test=100%") => "test=100%25" >> CGI.escape("test=100%") => "test%3D100%25"
So, its really depends on the issue you need to solve. But I would avoid using inspect for escaping.
Update - there is a dump, inspect uses that, and it looks like it is what you need:
>> "\n\t".dump => "\"\\n\\t\""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With