Skip to content

Latest commit

 

History

History
120 lines (89 loc) · 2.24 KB

ruby.md

File metadata and controls

120 lines (89 loc) · 2.24 KB

Ruby Style Guide

Borrowed heavily from the Github Ruby Styleguide.

Basic formatting

  • Use 2 space indentation (no hard tabs)
  • No trailing whitespace
  • Avoid exceeding 80 characters per line

Strings

  • Use single quotes, unless you need interpolation.

    "foobar" # bad
    'foobar' # good
  • When using string intepolation, don't use spaces before/after { and }.

    "foo{ bar }" # bad
    "foo{bar}"   # good
  • Use double quotes if the string contains single quotes.

    'Don\'t use single quotes here' # bad
    "Don't use single quotes here"  # good

Arrays and hashes

  • Use Ruby 1.9 hash syntax.

    numbers = { 'one' => 1, 'two' => 2, 'three' => 3 }     # bad
    numbers = { one: 1, two: 2, three: 3 }                 # good
  • Use literal array syntax for arrays of strings.

    STATES = ['new', 'approved', 'rejected'] # bad
    STATES = %w(new approved rejected)       # good

Conditions

  • Leave blank lines between if blocks.

    # Bad
    if some_condition?
      do_something
    if some_other_condition?
      do_something_else
    
    # Good
    if some_condition?
      do_something
    
    if some_other_condition?
      do_something_else
  • Use unless condition? instead of if !condition?.

  • Never use unless-else conditions. Replace it with if-else.

    # Bad
    unless success?
      puts 'failure'
    else
      puts 'success'
    end
    
    # Good
    if success?
      puts 'success'
    else
      puts 'failure'
    end

Blocks

  • Use { ... } blocks instead of single line do ... end blocks.

    # Bad
    manipulate! do |img|
      img.auto_orient!
    end
    
    # Good
    manipulate! { |img| img.auto_orient! }

Methods

  • Use parentheses around arguments in method definition.

    def foo bar   # bad
    def foo(bar)  # good
  • Don't use parentheses when there are no arguments.

    def foo()   # bad
    def foo     # good
  • Always use parentheses in method calls when there is a condition after it.

    foo(bar) if baz?  # good
    foo bar if baz?   # bad