Don't escape in Strings

Stop doing this:

"#{name} said: \"Clap your hands!\""

It’s ugly and you don’t need it. Ruby has excellent support for arbitrary delimiters for string literals. Above can be rewritten as:

%-#{@name} says: "Clap your hands!"-

… or if String contains dash:

%/#{@name} says: "Play tic-tac-toe!"/

… or if String contains dash and slash:

%Q|#{@name} says: "Try ftp://ruby-lang.org/pub/ruby/1.9/"|

… and so on. No need to escape.

The Ruby programming Language Book: The sequence %q begins a string literal that follows single-quoted string rules, and the sequence %Q (or just %) introduces a literal that follows double-qouted string rules. The first character following q or Q is the delimiter, and the string literal continues until a matching delimiter is found. If the opening delimiter is (, [, {, or <, then the matching delimiter is ), ], }, or >. Otherwise, the closing delimiter is the same as the opening delimiter.

Published 2008-10-26 · Home