跳至內容

Splat 展開和元組

方法可以使用展開參數*)接收可變數量的參數,該參數只能出現一次且可以在任何位置

def sum(*elements)
  total = 0
  elements.each do |value|
    total += value
  end
  total
end

sum 1, 2, 3      # => 6
sum 1, 2, 3, 4.5 # => 10.5

傳遞的參數在方法主體中會成為一個 Tuple

# elements is Tuple(Int32, Int32, Int32)
sum 1, 2, 3

# elements is Tuple(Int32, Int32, Int32, Float64)
sum 1, 2, 3, 4.5

展開參數之後的參數只能作為具名參數傳遞

def sum(*elements, initial = 0)
  total = initial
  elements.each do |value|
    total += value
  end
  total
end

sum 1, 2, 3              # => 6
sum 1, 2, 3, initial: 10 # => 16

展開參數之後沒有預設值的參數是必要的具名參數

def sum(*elements, initial)
  total = initial
  elements.each do |value|
    total += value
  end
  total
end

sum 1, 2, 3              # Error, missing argument: initial
sum 1, 2, 3, initial: 10 # => 16

兩個具有不同必要具名參數的方法會彼此多載

def foo(*elements, x)
  1
end

def foo(*elements, y)
  2
end

foo x: "something" # => 1
foo y: "something" # => 2

展開參數也可以不具名,表示「在此之後,接著是具名參數」

def foo(x, y, *, z)
end

foo 1, 2, 3    # Error, wrong number of arguments (given 3, expected 2)
foo 1, 2       # Error, missing argument: z
foo 1, 2, z: 3 # OK

展開元組

可以使用 *Tuple 展開到方法呼叫中

def foo(x, y)
  x + y
end

tuple = {1, 2}
foo *tuple # => 3

雙重展開和具名元組

雙重展開(**)會捕獲其他參數未匹配的具名參數。 參數的型別為 NamedTuple

def foo(x, **other)
  # Return the captured named arguments as a NamedTuple
  other
end

foo 1, y: 2, z: 3    # => {y: 2, z: 3}
foo y: 2, x: 1, z: 3 # => {y: 2, z: 3}

雙重展開具名元組

可以使用 **NamedTuple 展開到方法呼叫中

def foo(x, y)
  x - y
end

tuple = {y: 3, x: 10}
foo **tuple # => 7