Collections

  • Prefer map over
    collect.[link]

  • Prefer detect over find. The use of find
    is ambiguous with regard to ActiveRecord’s find method - detect makes
    clear that you’re working with a Ruby collection, not an AR object.
    [link]

  • Prefer reduce over inject.
    [link]

  • Prefer size over either length or count
    for performance reasons.[link]

  • Prefer literal array and hash creation
    notation unless you need to pass parameters to their constructors.
    [link]

    1. # bad
    2. arr = Array.new
    3. hash = Hash.new
    4. # good
    5. arr = []
    6. hash = {}
    7. # good because constructor requires parameters
    8. x = Hash.new { |h, k| h[k] = {} }
  • Favor Array#join over Array#* for clarity.
    [link]

    1. # bad
    2. %w(one two three) * ', '
    3. # => 'one, two, three'
    4. # good
    5. %w(one two three).join(', ')
    6. # => 'one, two, three'
  • Use symbols instead of strings as hash keys.
    [link]

    1. # bad
    2. hash = { 'one' => 1, 'two' => 2, 'three' => 3 }
    3. # good
    4. hash = { :one => 1, :two => 2, :three => 3 }
  • Relatedly, use plain symbols instead of string
    symbols when possible.[link]

    1. # bad
    2. :"symbol"
    3. # good
    4. :symbol
  • Use Hash#key? instead of
    Hash#has_key? and Hash#value? instead of Hash#has_value?. According
    to Matz, the longer forms are considered deprecated.
    [link]

    1. # bad
    2. hash.has_key?(:test)
    3. hash.has_value?(value)
    4. # good
    5. hash.key?(:test)
    6. hash.value?(value)
  • Use multi-line hashes when it makes the code
    more readable, and use trailing commas to ensure that parameter changes
    don’t cause extraneous diff lines when the logic has not otherwise changed.
    [link]

    1. hash = {
    2. :protocol => 'https',
    3. :only_path => false,
    4. :controller => :users,
    5. :action => :set_password,
    6. :redirect => @redirect_url,
    7. :secret => @secret,
    8. }
  • Use a trailing comma in an Array that
    spans more than 1 line[link]

    1. # good
    2. array = [1, 2, 3]
    3. # good
    4. array = [
    5. "car",
    6. "bear",
    7. "plane",
    8. "zoo",
    9. ]