Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to escape and unescape strings in Ruby?

Tags:

ruby

escaping

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?

like image 999
jwfearn Avatar asked Dec 26 '11 22:12

jwfearn


People also ask

How do you escape a string in Ruby?

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.

How do I remove an escape sequence from a string?

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-?]

What is %q in Ruby?

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.


2 Answers

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 \" \\" 
like image 139
christopheraue Avatar answered Oct 25 '22 18:10

christopheraue


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\"" 
like image 20
Stanislav O. Pogrebnyak Avatar answered Oct 25 '22 18:10

Stanislav O. Pogrebnyak