Ruby Line-Saving Tricks

Here are some tricks I use to remove unnecessary verboseness in my Ruby code without hurting the clarity, and hopefully even improving it.

Enumeration

Ruby doesn’t have an ‘enum’ like C does, so we’re stuck using constants, so we often see lists of constants such as:

UNIT_PIXELS = 0
UNIT_CENTIMETERS = 1
UNIT_INCHES = 2

However, using Ruby’s multi-asignment, we can instead write:

UNIT_PIXELS, UNIT_CENTIMETERS, UNIT_INCHES = 0, 1, 2

Or, perhaps easier (especially for long lists):

UNIT_PIXELS, UNIT_CENTIMETERS, UNIT_INCHES = (0..2).to_a

Multi-Require

Ruby’s require directive accepts a single file name to load, leading to this:

require ‘gtk2’
require ‘libglade2’
require ‘gconf2’

It would be nice if we could list these on one line. This is possible if we override Ruby’s require method in the Kernel module:

module Kernel
  alias_method :single_require, :require
  def require(*list)
    list.each { |file| single_require(file) }
  end
end

Now we can write:

require ‘gtk2’, ‘libglade2’, ‘gconf2’

Hopefully a future Ruby version will support this syntax without the hack!

4 Responses to Ruby Line-Saving Tricks

  1. Jeremy Cole says:

    You can do this in PHP and Perl as well:

    PHP: list($a, $b, $c) = array(1, 2, 3);

    Perl: ($a, $b, $c) = (1, 2, 3);

  2. Ulysses says:

    You could also do %w(gtk2 libglade2 gconf2).each(&Kernel.method :require) for fun.

  3. ianmcintosh says:

    Jeremy, is it possible to define constants that way in PHP? I think it requires this syntax:

    define(‘UNIT_PIXEL’, 0);

    Tell me if I’m wrong, it has been a while since I’ve written anything new in PHP. Regardless, one has to appreciate the simplicity of:

    A, B, C = 1, 2, 3

    Ulysses, interesting, I didn’t know you could pass a method to array::each but it makes perfect sense. I’m not sure which is more clear.

    I’ve never understood why ruby has the %w syntax. I like the form [‘gtk2’, ‘libglade2’, ‘gconf2’] because it makes it obvious exactly what it is: an array with three strings.

  4. […] Note that this also adds multi-file “require”, which I discussed earlier. […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: