* : 叫做 splat operator
**: double splat operator
single splat 用法1:
a, b = 1,2
a, b = *[1,2]
一样的。分别赋值
single splat 用法2: 作为方法的参数,该参数是一个value (注意不是hash)
def print_words(*words)
words.each { |word| puts word }
end
print_words("one", "two", "three", "four")
会打印所有的参数 => "one", "two", "three", "four"
表示:
该参数是个数组,可选,长度无限,不能一个方法的参数中出现两次。
double splat 用法: 作为方法的参数,该参数是一个hash , 可选
例如;
def foo(a, *b, **c)
[a, b, c]
end
Here's a demo:
> foo 10
=> [10, [], {}]
> foo 10, 20, 30
=> [10, [20, 30], {}]
> foo 10, 20, 30, d: 40, e: 50
=> [10, [20, 30], {:d=>40, :e=>50}]
> foo 10, d: 40, e: 50
=> [10, [], {:d=>40, :e=>50}]
可以看出, *b 需要的是 数组 1,2,3 这样, **c 需要的是一个 hash ,传入的时候都不需要最外侧的 [] 或者 {}