Best way to escape and unescape strings in Ruby?
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 \" \\"
String literal without need to escape backslash
There is somewhat similar thing available in Ruby. E.g.
foo = %Q(The integer division operator in VisualBASIC is written "a \\ b" and #{'interpolation' + ' works'})
You can also interpolate strings in it. The only caveat is, you would still need to escape \
character.
HTH
How to escape strings for terminal in Ruby?
Shellwords should work for you :)
exec "/usr/bin/mplayer %s" % Shellwords.escape(song.file)
In ruby 1.9.x, it looks like you have to require
it first
require "shellwords"
But in ruby 2.0.x, I didn't have to explicitly require it.
escaping a string in Ruby
Don't use multiple methods - keep it simple.
Escape the #, the backslash, and the double-quote.
irb(main):001:0> foo = "`~!@\#$%^&*()_-+={}|[]\\:\";'<>?,./"
=> "`~!@\#$%^&*()_-+={}|[]\\:\";'<>?,./"
Or if you don't want to escape the # (the substitution character for variables in double-quoted strings), use and escape single quotes instead:
irb(main):002:0> foo = '`~!@#$%^&*()_-+={}|[]\\:";\'<>?,./'
=> "`~!@\#$%^&*()_-+={}|[]\\:\";'<>?,./"
%q is great for lots of other strings that don't contain every ascii punctuation character. :)
%q(text without parens)
%q{text without braces}
%Q[text without brackets with #{foo} substitution]
Edit: Evidently you can used balanced parens inside %q() successfully as well, but I would think that's slightly dangerous from a maintenance standpoint, as there's no semantics there to imply that you're always going to necessarily balance your parens in a string.
How do I escape #{ from string interpolation
I think the backslash-hash is just Ruby being helpful in some irb-only way.
>> a,b = 1,2 #=> [1, 2]
>> s = "#{a} \#{b}" #=> "1 \#{b}"
>> puts s #=> 1 #{b}
>> s.size #=> 6
So I think you already have the correct answer.
Removing backslash (escape character) from a string
When you write:
input = "{ \"foo\": \"bar\", \"num\": 3}"
The actual string stored in input is:
{ "foo": "bar", "num": 3}
The escape \"
here is interpreted by Ruby parser, so that it can distinguish between the boundary of a string (the left most and the right most "
), and a normal character "
in a string (the escaped ones).
String#delete
deletes a character set specified the first parameter, rather than a pattern. All characters that is in the first parameter will be removed. So by writing
input.delete('\\"')
You got a string with all \
and "
removed from input
, rather than a string with all \"
sequence removed from input
. This is wrong for your case. It may cause unexpected behavior some time later.
String#gsub
, however, substitute a pattern (either regular expression or plain string).
input.gsub('\\"', '')
means find all \"
(two characters in a sequence) and replace them with empty string. Since there isn't \
in input
, nothing got replaced. What you need is actually:
input.gsub('"', '')
Is is possible to create a string in ruby that keeps escaping characters?
You can use the %q
delimiter rather than "
:
def user_data
%q[#!/bin/bash
sed -i -e '/<Name>loadbalanceServerIP<\/Name>/,/<Value>/s/<Value>[^<]*/<Value>1.1.1.1/' /home/wowza/conf/Server.xml]
end
How to print an escape character in Ruby?
Use String#inspect
puts word.inspect #=> "x\nz"
Or just p
p word #=> "x\nz"
Related Topics
Rspec: Testing Assignment of Instance Variable
Built in Way to List Directories in a Directory in Ruby
How to Sort a Ruby Array of Strings by Length
Ending a Rails 2 Url with an Ip Address Causes Routing Error
Are There Ruby Equivalents to Car, Cdr, and Cons
Add a Callback Function to a Ruby Array to Do Something When an Element Is Added
Machinist VS Factorygirl - Pros and Cons
Is It a Bad Idea to Reload Routes Dynamically in Rails
How to Color Unit Tests with Lib Minitest or Test:Unit
Ruby on Rails: Conditionally Display a Partial
Rails Activerecord Query Date Range
Testing Simple Sti with Factorygirl
In Ruby What Is the Meaning of Colon After Identifier in a Hash
Ruby - Remove Pattern from String
How to Set the Httponly Flag on a Cookie in Ruby on Rails