Ruby Shortcuts

2010-03-18 22:32:45

There's a few useful shorthand ways to create certain objects in Ruby, a couple of obvious ones are [] to create an Array and {} to create a Hash (Or block/Proc). There's some not so obvious ones too, for creating strings, regexes and executing shell commands.

With all of the examples I've used {} as the delimiter characters, but you can use a variety of characters. Personally I tend to use {} unless the string contains them, in which case I'll use // or @@. My only exception appears to be %w, for which I tend to use ().

Strings

% and %Q are the same as using double quotes, including string interpolation. Really useful when you want to create a string that contains double quotes, but without the hassle of escaping them.

%{}                 # => ""
%Q{}                # => ""

%{caius}            # => "caius"
%{caius #{5}}       # => "caius 5"
%{some "foo" thing} # => "some \"foo\" thing"

%q is equivalent to using single quotes. Behaves exactly the same, no string interpolation.

%q{}           # => ''
%q{caius}      # => "caius"
%q{caius #{5}} # => "caius \#{5}"

Arrays

%w is the equivalent of using String#split. It takes a string and splits it on whitespace. With the added bonus of being able to escape whitespace too. %W allows string interpolation.

%w(foo bar sed)  # => ["foo", "bar", "sed"]
%w(foo\ bar sed) # => ["foo bar", "sed"]
%W(foo #{5} bar) # => ["foo", "5", "bar"]

Regexes

%r is just like using // to create a regexp object. Comes in handy when you're writing a regex containing / as you don't have to continually escape it.

%r{foo|bar} # => /foo|bar/
%r{foo/bar} # => /foo\/bar/

Symbols

%s creates a symbol, just like writing :foo manually. It takes care of escaping the symbol, but unlike :"" it doesn't allow string interpolation however.

%s{foo}      # => :foo
%s{foo/bar}  # => :"foo/bar"
:"foo-#{5}"  # => :"foo-5"
%s{foo-#{5}} # => :"foo-\#{5}"

Shelling out

%x is the same as backticks (``), executes the command in a shell and returns the output as a string. And just like backticks it supports string interpolation.

`echo hi`     # => "hi\n"
%x{echo hi}   # => "hi\n"
%x{echo #{5}} # => "5\n"

10 Comments on Ruby Shortcuts

  1. Oddly, what I learned from this wasn't new shortcuts as I believe I had seen them all before, but the fact that you can use different delimiters! This detail had escaped me.

  2. Don't forget the sprintf shortcut--these are equivalent:

    sprintf("%5.1f", 345.6789) # "345.7"
    "%5.1f" % 345.6789 # "345.7"

    as are these:

    sprintf("%6.2f, %05d", 345.6789, 123) # "345.68, 00123"
    "%6.2f, %05d" % [345.6789, 123] # "345.68, 00123"
  3. @ed: That isn't strictly a shortcut in the way the others are, it's a method on String. String#% to be precise :)

  4. True, but it is kinda cool and not very well-known, don'cha think? :)

  5. Timely find for me, I've working on a website where there are a lot of pre-existing articles to post and have been furiously escaping either " or ' . What a pain! I didn't know about using the %Q{} to avoid the mess. THANKS!

  6. @Ed: I guess it isn't that well known, I've just read the String documentation a fair bit and know most of the methods in there ;) Still great to point it out to people though!

    @FlyboyArt: I'm glad I could help! My "justification" for blogging is if it helps just one person, it was worth sharing. :)

  7. I've found that carets (^) work quite well as delimiters. I rarely use them in text.

  8. I was curious so other people might be too: %W doesn't split interpolated strings.

    %W(foo #{'x y'} bar) # => ["foo", "x y", "bar"]
  9. Hi Caius, this is a very interesting post.

    So interesting that I think it's worth to reproduce your thoughts as a screencast. Check out RubyPulse Episodes 0.33 + 0.34 ... so... actually your post is woth TWO screencasts ;-) GREAT!

    ~ aaalex

  10. Thanks a lot Caius.

    I've learned a lot in your post. Moreover, it helped me fixing some parts inside my highlighter (see ie http://prism-pastebin.heroku.com/28)

About You
Comment