rors.org

Personal website of Dejan Simic, a Ruby On Rails developer working for Less Everything

Don't escape in Strings

So don’t do:

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

It’s ugly and you don’t need it. Ruby has excellent support for arbitrary delimiters for string literals.

So 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.


Excerpt from the great book The Ruby programming Language:

“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.”

Any thoughts?



Fork me on GitHub