跳至內容

預設參數值與具名引數

預設參數值

方法可以為最後的參數指定預設值

class Person
  def become_older(by = 1)
    @age += by
  end
end

john = Person.new "John"
john.age # => 0

john.become_older
john.age # => 1

john.become_older 2
john.age # => 3

具名引數

除了位置之外,所有引數也可以透過其名稱指定。 例如:

john.become_older by: 5

當有很多引數時,調用中名稱的順序並不重要,只要涵蓋了所有必要的參數即可

def some_method(x, y = 1, z = 2, w = 3)
  # do something...
end

some_method 10                   # x: 10, y: 1, z: 2, w: 3
some_method 10, z: 10            # x: 10, y: 1, z: 10, w: 3
some_method 10, w: 1, y: 2, z: 3 # x: 10, y: 2, z: 3, w: 1
some_method y: 10, x: 20         # x: 20, y: 10, z: 2, w: 3

some_method y: 10 # Error, missing argument: x

當方法指定展開參數(在下一節中說明)時,具名引數不能用於位置參數。原因是理解引數如何匹配變得非常困難;在這種情況下,位置引數更容易推理。