在Ruby中,用于参数列表的伪正则表达式(同样适用于方法、块和lambda字面值)类似于以下内容:
mand* opt* splat? mand* (mand_kw | opt_kw)* ksplat? block?
这里是一个例子:
def foo(m1, m2, o1=:o1, o2=:o2, *splat, m3, m4,
ok1: :ok1, mk1:, mk2:, ok2: :ok2, **ksplat, &blk)
Hash[local_variables.map {|var| [var, eval(var.to_s)] }]
end
method(:foo).arity
method(:foo).parameters
foo(1, 2, 3, 4)
foo(1, 2, 3, mk1: 4, mk2: 5)
foo(1, 2, 3, 4, mk1: 5, mk2: 6)
foo(1, 2, 3, 4, 5, mk1: 6, mk2: 7)
foo(1, 2, 3, 4, 5, 6, mk1: 7, mk2: 8)
foo(1, 2, 3, 4, 5, 6, 7, mk1: 8, mk2: 9)
foo(1, 2, 3, 4, 5, 6, 7, 8, mk1: 9, mk2: 10)
foo(1, 2, 3, 4, 5, 6, 7, 8, ok1: 9, mk1: 10, mk2: 11)
foo(1, 2, 3, 4, 5, 6, 7, 8, ok1: 9, mk1: 10, mk2: 11, ok2: 12)
foo(1, 2, 3, 4, 5, 6, 7, 8, ok1: 9, mk1: 10, mk2: 11, ok2: 12, k3: 13)
foo(1, 2, 3, 4, 5, 6, 7, 8,
ok1: 9, mk1: 10, mk2: 11, ok2: 12, k3: 13, k4: 14)
foo(1, 2, 3, 4, 5, 6, 7, 8,
ok1: 9, ok2: 10, mk1: 11, mk2: 12, k3: 13, k4: 14) do 15 end
[注意:Ruby 2.1将引入强制关键字参数,其余部分已经可以正常工作。]
**
符号来表示“任意关键字参数”,所以我也添加了这些。 - Patrick Oscity