Default parameter values and named arguments

Default parameter values

A method can specify default values for the last parameters:

  1. class Person
  2. def become_older(by = 1)
  3. @age += by
  4. end
  5. end
  6. john = Person.new "John"
  7. john.age # => 0
  8. john.become_older
  9. john.age # => 1
  10. john.become_older 2
  11. john.age # => 3

Named arguments

All arguments can also be specified, in addition to their position, by their name. For example:

  1. john.become_older by: 5

When there are many arguments, the order of the names in the invocation doesn’t matter, as long as all required parameters are covered:

  1. def some_method(x, y = 1, z = 2, w = 3)
  2. # do something...
  3. end
  4. some_method 10 # x: 10, y: 1, z: 2, w: 3
  5. some_method 10, z: 10 # x: 10, y: 1, z: 10, w: 3
  6. some_method 10, w: 1, y: 2, z: 3 # x: 10, y: 2, z: 3, w: 1
  7. some_method y: 10, x: 20 # x: 20, y: 10, z: 2, w: 3
  8. some_method y: 10 # Error, missing argument: x

When a method specifies a splat parameter (explained in the next section), named arguments can’t be used for positional parameters. The reason is that understanding how arguments are matched becomes very difficult; positional arguments are easier to reason about in this case.