How to Escape Strings for Terminal in Ruby

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.

Ruby escape ARGV argument or string as argument to shell command

Use require 'shellwords' and Shellwords.escape, which will fix this sort of stuff for you:

http://apidock.com/ruby/Shellwords/shellescape

Ruby /& in a String

When you see Ruby showing something like:

"asdf \\& asdf"

That's broken up into the tokens \\ (backslash) and & (ampersand) where the first backslash is special, the second is an actual character. You can read this as "literal backslash".

When printed you're seeing the actual string. It's correct.

Internally the double backslashes aren't actually there, it's just a consequence of how double-quoted strings must be handled.

This is to ensure that \n and \r and other control characters work, but you're also able to put in actual backslashes. There's a big difference between \n (newline) and \\n (literal backslash letter n).

You'll see this often when dealing with data formats that have special characters. For example, in printf style formatters % is significant, so to print an actual % you need to double it up:

'%.1f%%' % 10.3
#=> "10.3%"

Each format will have its own quirks and concerns. HTML doesn't treat backslash as special, but it does < and > and &, so you'll see & instead of ampersand.

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.



Related Topics



Leave a reply



Submit