在这个Ruby代码中,(一元)*操作符是做什么的?

在这个Ruby代码中,(一元)*操作符是做什么的?

给定Ruby代码

line = "first_name=mickey;last_name=mouse;country=usa" record = Hash[*line.split(/=|;/)]

我明白第二行的每一件事,除了*操作员-它在做什么,它的文档在哪里?(你可能猜到,寻找这个案子很难.)



噜噜哒
浏览 442回答 3
3回答

catspeake

Splat运算符解压缩传递给函数的数组,以便将每个元素作为单独的参数发送给函数。一个简单的例子:>> def func(a, b, c)>>   puts a, b, c>> end=> nil>> func(1, 2, 3)  #we can call func with three parameters123=> nil>> list = [1, 2, 3]=> [1, 2, 3]>> func(list) #We CAN'T call func with an array, even though it has three objectsArgumentError: wrong number of arguments (1 for 3)    from (irb):12:in 'func'    from (irb):12>> func(*list) #But we CAN call func with an unpacked array.123=> nil就这样!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Ruby