Ruby Percent Syntax (Percent Functions)

I wanted to post a quick guide to the special ruby syntax for literals that utilize the % (percent) symbol. Most beginners guides to ruby leave out an explanation of these forms of literals, but many ruby coders use them. When someone encounters them for the first time it is almost impossible to figure out what they mean. (Try searching Google for “%w”)

Ruby has special syntax for making strings, arrays and system commands easier to write. They allow you to use different characters as delimiters so you can minimize escaping in your literals.

The syntax

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

The delimiter can be any character, and is defined as whatever 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 (, 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 double-quoted ruby string. #{expression} evaluation works just like in double-quoted strings, even if you use %Q{} as your delimiter!

You can also leave off the Q and it will have the same functionality. I recommend leaving the Q in to be more clear.

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

You can remember %Q is for strings because it acts like Quotes.

More info here: http://docs.huihoo.com/ruby/ruby-man-1.4/syntax.html#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 delimiter rules are the same as strings, but typically parentheses are used. The content inside the delimiters are split by white-space, and put into an array. This is great if you have a hard coded list of single word strings.

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

You can remember %W is by thinking of it as a White-space divided Array.

More info here : http://docs.huihoo.com/ruby/ruby-man-1.4/syntax.html#array

%x (Percent x): System Execution

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

%x allows you to call system commands, equivilent to wrapping the command in `s (grave accents). The benefit of the $x{} syntax is you don’t have to escape your accents in commands that use them.

You can remember to use X because it eXecutes a command.

More info here: http://docs.huihoo.com/ruby/ruby-man-1.4/syntax.html#command

%r (Percent r): Regular Expressions

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

%r is really handy for regular expressions that contain /s (forward slashes) which are the default delimiter for regular expressions and have to be escaped.

Remember to use %r with regular expressions.

More info here: http://docs.huihoo.com/ruby/ruby-man-1.4/syntax.html#regexp

I hope this information is helpful. Please leave a comment if this helped or if I left something out.

Tags: , , ,

12 Responses to “Ruby Percent Syntax (Percent Functions)”

  1. Andy Says:

    Thank you!

  2. Ishmael Says:

    Thanks! I am a newbie, who just noticed it in the ri of Arrays, and was like, “Huh, What!”

  3. Josh Shomo Says:

    Great guide. It’s always easier for me to understand when someone breaks it down into a form like this.

    The only thing I would add is that %W treats the strings as double quoted whereas %w treats them as single quoted (and therefore won’t interpolate expressions or numerous escape sequences). Also, I think you accidentally typed “user” instead “usr” in the %r section.

  4. Jim Hoskins Says:

    Thanks Josh!

    I didn’t know the difference between %w and %W. I have update the post with that fact.

  5. blindgaenger Says:

    I was just about writing something about them by myself. But now I haven’t to. Thanks! :)

    BTW: you missed the notation for symbols

    >> %s(some symbol)
    => :”some symbol”

  6. blindgaenger Says:

    Alright, I also created an entry in http://cheat.errtheblog.com/s/ruby_percent

    Cheers!

  7. Mark Says:

    @blindgaenger - Thanks for the link. Rails Recipes uses the %(…) sytax to output results from a helper. I didn’t see an explanation in the book, but glad I found it explained on your site.

  8. Adam Gardner Says:

    I believe (though of course I could be wrong) that the ‘w’ in ‘%w’ stands for ‘Words’, not ‘whitespace’. Also, you left [ and ] out of your list of delimiters which use left/right pairing.

  9. bws12r Says:

    Thanks. The only useful link about this issue.

  10. Benjamin Manns Says:

    Thank you for using Google-friendly headings (percent w versus %w)! I have search for a long time for things similar to this.

  11. Kyle Heironimus Says:

    Thanks. Google found it for me, after using the word “percent.”

  12. Gabrielle Brentlinger Says:

    Fed up with getting low amounts of useless visitors for your site? Well i wish to tell you about a new underground tactic that makes myself $900 per day on 100% AUTOPILOT. I possibly could be here all day and going into detail but why dont you merely check their site out? There is really a excellent video that explains everything. So if your serious about producing simple hard cash this is the site for you. Auto Traffic Avalanche

Leave a Reply