Skip to content

Ruby Style Guide

connorshea edited this page Nov 29, 2014 · 5 revisions

Formatting

Indent with 2 spaces. NEVER USE TABS.

def good
  return true
end

Always add a trailing newline to the end of a file.

Try your best not to go over 80 character line widths.

When nesting multiple blocks, use one end per line:

def good
  example do |x|
    puts x
  end
end

Leave one newline between methods in a class. Add documentation comments for the methods in a class above where they are declared. Do not add newlines between the start of a class and the start of the first method, or the end of the last method and the end of a class.

class Format
  ##
  # Initialize with an example formatter 
  def initialize(formatter)
    @formatter = formatter
    @formatter.test!
  end

  def test(str)
    @formatter.test(str).map do |x|
      x.format!
    end
  end
end

When chaining methods on multiple lines, put the dot before the method:

foo.bar
   .baz
   .test
   .image
   .select{|x| x > 3}

Conventions, Constructs, and Naming

You should never have to use a for in loop. Use constructs like .each instead.

Prefer transformations like map and select over loops.

Use snake_case for variable and method names, and CamelCase for object names.

When working with numbers, it is okay to use the single-letter variable names x, y, or z. This is especially true in blocks:

my_numbers.sort{|x, y| y <=> x }

Clone this wiki locally