Hi, I'm Blake Williams

I'm a full-stack developer living in Boston, MA.

*full-stack meaning I really enjoy writing Rails, Elixir, React (Native), and sometimes HTML & (S)CSS.

October 2012
#ruby

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.