使用双 splat 运算符**
作为参数的好处主要是您可以完全避免传递任何参数。与使用单个 splat 运算符时发生的情况非常相似*
。
使用您的示例并调用:
test "s"
# raises ArgumentError (wrong number of arguments (given 1, expected 2))
test_two "s"
# works, prints `{} Hash`
这在您希望有一个“主要”参数的方法中很有用,通常是一些选项,而不会使参数空间混乱。例如,想象一个 CSV 行解析器:
def parse_row_1(row, **options)
separator = options.fetch :separator, ","
quote_char = options.fetch :quote_char, null
# ...
end
def parse_row_2(row, separator = ",", quote_char = null)
# ...
end
# To parse a string like this:
s = "'ABC','123','DEF'"
# With ** method you can do just this:
parse_row_1 s, quote_char: "'"
# Without ** you must specify every time the arguments, because they are positional:
parse_row_2 s, ",", "'"