@キャスパーは正しいです。パラメータの 1 つだけが、splat 演算子を持つことができます。引数は、最初に左から右に分割されていないパラメーターに割り当てられます。残りの引数は、splat パラメータに割り当てられます。
あなたは彼が提案するようにすることができます。これを行うこともできます:
def test(id,h={},*a)
# do something with id
# if not h.empty? then do something with h end
# if not a.empty? then do something with a end
end
irb 実行のサンプルを次に示します。
001 > def test (id, h={}, *a)
002?> puts id.inspect
003?> puts h.inspect
004?> puts a.inspect
005?> end
=> nil
006 > test(1,2,3,4)
1
2
[3, 4]
=> nil
007 > test(1,{"a"=>1,"b"=>2},3,4)
1
{"a"=>1, "b"=>2}
[3, 4]
=> nil
008 > test(1,nil,3,4)
1
nil
[3, 4]
=> nil
おそらく、私は追加する必要があります。オプションのパラメーターを最後のパラメーターとして使用できますが、ブロック/プロシージャである必要があります。
例えば:
def test(a,*b, &c)
puts a.inspect
puts b.inspect
c.call if not c.nil?
end
呼び出しの例を次に示します。
006 > test(1,2,3)
1
[2, 3]
=> nil
007 > test(1,2,3) {puts "hello"}
1
[2, 3]
hello
=> nil