Ruby styleguide

Code conventions and patterns to make your code easily readable.

Coding Style

  • Use soft-tabs with a two space indent.
  • Keep lines fewer than 80 characters.
  • Never leave trailing whitespace.
  • End each file with a blank newline.
  • Use CamelCase for classes and modules, snake_case for variables and methods, SCREAMING_SNAKE_CASE for constants.
  • Use spaces around operators, after commas, colons and semicolons, around { and before }.
  • No spaces after (, [ or before ], ).
  • No spaces after !.
  • Indent when as deep as case.
  • Use empty lines between defs and to break up a method into logical paragraphs.
  def some_method
    data = initialize(options)

    data.manipulate!

    data.result
  end

  def some_method
    result
  end

Syntax

  • Avoid explicit return statements.
  • Use each, not for, for iteration.
  • Use {...} for single-line blocks. Use do..end for multi-line blocks.
  • Prefer &:method_name to { |item| item.method_name } for simple method calls.
  • Prefer && and || over and and or. [link]
  • Use def self.method, not def Class.method or class << self
  • Use def with parentheses when there are arguments

References

Further Reading

Using “and” and “or” in Ruby