Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

escaping a string in Ruby

Tags:

ruby

I want to insert the following as the value for a variable in some Ruby:

`~!@#$%^&*()_-+={}|[]\:";'<>?,./

Surrounding this in double quotes doesn't work, so is there a nice escape_until_the_end sort of thing available?

like image 551
Neil Middleton Avatar asked Oct 27 '09 23:10

Neil Middleton


1 Answers

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.

like image 110
James Baker Avatar answered Oct 04 '22 00:10

James Baker