双 * (splat) 运算符有什么作用 [英] What does a double * (splat) operator do
本文介绍了双 * (splat) 运算符有什么作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你见过这样声明的函数吗?
Have you seen a function declared like this?
def foo a, **b
...
end
我知道单个 *
是 splat 运算符.**
是什么意思?
I understand that a single *
is the splat operator. What does **
mean?
推荐答案
Ruby 2.0 引入了关键字参数,而 **
的作用类似于 *
,但用于关键字参数.它返回一个带有键/值对的哈希.
Ruby 2.0 introduced keyword arguments, and **
acts like *
, but for keyword arguments. It returns a Hash with key / value pairs.
对于此代码:
def foo(a, *b, **c)
[a, b, c]
end
这是一个演示:
> 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}]
这篇关于双 * (splat) 运算符有什么作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文