Methods

Methods

Method definitions

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

   def some_method_with_parameters(arg1, arg2)
     # body omitted
   end
  • Do not use default positional arguments.
    Use keyword arguments (if available - in Ruby 2.0 or later) or an options
    hash instead.[link]
  # bad
  def obliterate(things, gently = true, except = [], at = Time.now)
    ...
  end

  # good
  def obliterate(things, gently: true, except: [], at: Time.now)
    ...
  end

  # good
  def obliterate(things, options = {})
    options = {
      :gently => true, # obliterate with soft-delete
      :except => [], # skip obliterating these things
      :at => Time.now, # don't obliterate them until later
    }.merge(options)

    ...
  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]
  # bad
  def too_much; something; something_else; end

  # good
  def some_method
    # body
  end

Method calls

Use parentheses for a method call:

  • If the method returns a value.
    [link]
  # bad
  @current_user = User.find_by_id 1964192

  # good
  @current_user = User.find_by_id(1964192)
  • If the first argument to the method uses
    parentheses.[link]
  # bad
  put! (x + y) % len, value

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

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

  # good
  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]
  # okay
  render(:partial => 'foo')

  # okay
  render :partial => 'foo'

In either case:

  • If a method accepts an options hash as the
    last argument, do not use { } during invocation.
    [link]
  # bad
  get '/v1/reservations', { :id => 54875 }

  # good
  get '/v1/reservations', :id => 54875