Russ Smith home

Ruby Style Guide

Naming Conventions

Constants use upper case, for example

  Math::PI
  Curses::KEY_DOWN
  OptionParser::REQUIRED_ARGUMENT
  

Classes use camel case — join words of class names by capitalizing the first letter of each word. The same goes for ModuleNames as well.

Methods use underscores, as do local_variables, @instance_variables, and @@class_variables — join words with underscores (aka "snake_case")

Keep acronyms in class names capitalized. MyXMLClass, not MyXmlClass. Variables should use all lower-case.

There is no place in Ruby where lowerCamelCase is ever used.

Whitespace

Use two spaces for indentation. If using an editor, set it to expand tabs to two spaces.

Statements that extend past 80 characters or so should be broken up and indented on the following line.

  a_very_long_method_name(argument1,
                          a + b,
                          arg 3)
  

Parenthesis

Ruby allows you to leave out parenthesis, in general, resist the temptation, except in the following cases:

  1. Always leave out empty parentheses.
  2. The parentheses can be left out of a single command that is surrounded by ERb delimiters -- the ERb markers make sure the code is still readable.

Block Formatting

There are two prevailing conventions on when to use curly braces for blocks versus the do ... end keywords:

  1. Use curly braces for one-line blocks, use do...end for multi-line blocks
  2. Use curly braces when the return value is desired (or chained), use do...end when the side-effect is desired.

  list.map { |x| x + 3 }

  list.map { |x|
    x + 3
  }.sort
  

If expressions

Use if statements as expressions.

  x = if boolean then 3 else 5 end
  x = boolean ? 3 : 5
  

Trailing if Statements

Only use trailing if statements in guard clauses.

  return if x.nil?
  

In general, these statements can get hard to read (people tend to overlook the if part) and should only be used if:

  1. The statement and the conditional are both simple.
  2. The statement is a guard clause that prevents execution of the rest of the method -- this can save a level of indent and make the method easier to read.

Use Ruby Idioms

There are a couple of idioms that, although they are sort of opaque the first time you see them, are commonly used enough that they should be used in place of wordier alternatives. Right now the list starts at three:

  @user ||= User.find(params[:id])
  @user.name &&= @user.name.downcase
  array.map(&:upcase)
  

References