October
22nd,
2012
I Love Percent Syntax and So Should You
As a Rails developer I sometimes deal with a lot of strings in various ways and it’s a huge pain when the strings require interpolation contain a lot of double quotes. Instead of escaping all of those double quotes you should use percent syntax. Ruby percent syntax gets past this by allowing you to use nearly any character as the delimiter for your string and works with non-interpolated strings, interpolated strings, regular expressions, arrays, and even shell commands.
Here are examples of each of the percent syntaxes.
string = %q[This has no interpolation]
string = %Q[This has interpolation]
array = %w[This creates an array split by whitespace with no interpolation]
array = %W[This creates an array split by whitespace with interpolation]
regex = %r[regex with interpolation]
string = %x[echo shell command with interpolation]
symbol = %s[symbol with no interpolation]
By using these you can make your code look a lot cleaner by avoiding the need to escape all of your double quotes or being forced to concatenate strings together to achieve the same effect.