chillibear.com

Ruby Percent Syntax (Percent Functions)

I was trying to find a decent reference to Ruby’s percent functions, but alas trying to google for ‘%w’ doesn’t get you very far. After a while I did come across http://old.blog.jimhoskins.com/?p=8, but at the time of writing the site isn’t available. So this is a quick summary of the content from that blog, reworked in places for future reference.

It’s possible in Ruby to create certain strings and arrays and indeed system commands easier to write by allowing the use of alternative deliminators, meaning less escaping and hopefully more readable code. This is all done via the percent syntax.

The syntax for the % literal is a percent symbol (%) followed by a letter which defines what kind of literal it is (Q, q, w, x, r) then a delimiter, then the content, and finally the closing delimiter.

The delimiter can be pretty much any character, and is defined as whatever character is immediately after the letter in the syntax. For example %Q!content! , the delimiter is the ! and it surrounds the content. There are special cases when the delimiter is { or (, in those cases the closing delimiter will be } or ) respectively.

%Q and %q (Percent Q): Strings

%Q!Some String of "Characters"! <==> "Some String of \"Characters\""

%Q is the equivalent to a normal double-quoted ruby string so markup like #{expression} works. You can actually also leave off the Q and it will have the same functionality.

%q!Some String of "Characters"! <==> 'Some String of "Characters"'

The %q is just like %Q, but acts the same as a single-quoted string. Whatever is inside the delimiters is returned as a string.

%W (Percent W): Arrays

%W(North South East West) <==> ["North", "South", "East", "West"]

%W (and %w) allow you to create an Array of strings without using quotes and commas.

The content inside the delimiters are split by white-space, and put into an array.

When using %W, it is evaluated as a double-quoted string. This allows you to use #{} to interpolate values. %w will evaluate as a single quoted string.

%x (Percent x): System Execution

%x{ ls /usr/local } <==> `ls /usr/local`

%x allows you to call system commands, equivalent to wrapping the command in backticks (`), or grave accents if we’re going to be more formal.

%r (Percent r): Regular Expressions

%r{/usr/bin/} <==> /\/usr\/bin\//

%r is useful for regular expressions that contain forward slashes (/) which of course are the normal delimiter for regular expressions and would therefore have to be escaped.

Written on 11 Mar 2012 and categorised in Ruby, tagged as

Home, Post archive

site copyright Eric Freeman

Valid XHTML 1.0 Strict