Methods

Method definitions

  • Use def with parentheses when there are
    parameters. Omit the parentheses when the method doesn’t accept any
    parameters.[link]

    1. def some_method
    2. # body omitted
    3. end
    4. def some_method_with_parameters(arg1, arg2)
    5. # body omitted
    6. end
  • Do not use default positional arguments.
    Use keyword arguments (if available - in Ruby 2.0 or later) or an options
    hash instead.[link]

    1. # bad
    2. def obliterate(things, gently = true, except = [], at = Time.now)
    3. ...
    4. end
    5. # good
    6. def obliterate(things, gently: true, except: [], at: Time.now)
    7. ...
    8. end
    9. # good
    10. def obliterate(things, options = {})
    11. options = {
    12. :gently => true, # obliterate with soft-delete
    13. :except => [], # skip obliterating these things
    14. :at => Time.now, # don't obliterate them until later
    15. }.merge(options)
    16. ...
    17. end
  • Avoid single-line methods. Although
    they are somewhat popular in the wild, there are a few peculiarities about
    their definition syntax that make their use undesirable.
    [link]

    1. # bad
    2. def too_much; something; something_else; end
    3. # good
    4. def some_method
    5. # body
    6. end

Method calls

Use parentheses for a method call:

  • If the method returns a value.
    [link]

    1. # bad
    2. @current_user = User.find_by_id 1964192
    3. # good
    4. @current_user = User.find_by_id(1964192)
  • If the first argument to the method uses
    parentheses.[link]

    1. # bad
    2. put! (x + y) % len, value
    3. # good
    4. put!((x + y) % len, value)
  • Never put a space between a method name and
    the opening parenthesis.[link]

    1. # bad
    2. f (3 + 2) + 1
    3. # good
    4. f(3 + 2) + 1
  • Omit parentheses for a method call if the
    method accepts no arguments.[link]

    1. # bad
    2. nil?()
    3. # good
    4. nil?
  • If the method doesn’t return a value (or we
    don’t care about the return), parentheses are optional. (Especially if the
    arguments overflow to multiple lines, parentheses may add readability.)
    [link]

    1. # okay
    2. render(:partial => 'foo')
    3. # okay
    4. render :partial => 'foo'

In either case:

  • If a method accepts an options hash as the
    last argument, do not use { } during invocation.
    [link]

    1. # bad
    2. get '/v1/reservations', { :id => 54875 }
    3. # good
    4. get '/v1/reservations', :id => 54875