(一元)*运算符在这个Ruby代码中做了什么?

时间:2009-05-27 23:17:52

标签: ruby operators splat

鉴于Ruby代码

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

除了*运算符之外,我理解第二行中的所有内容 - 它在做什么以及文档在哪里? (正如你可能猜到的那样,寻找这个案子很难......)

3 个答案:

答案 0 :(得分:254)

* splat 运算符。

它将Array扩展为参数列表,在本例中为Hash.[]方法的参数列表。 (更准确地说,它扩展了响应Ruby 1.9中的to_ary / to_ato_a的任何对象。)

为了说明,以下两个陈述是相同的:

method arg1, arg2, arg3
method *[arg1, arg2, arg3]

它也可以在不同的上下文中使用,以捕获方法定义中的所有剩余方法参数。在这种情况下,它不会扩展,但结合起来:

def method2(*args)  # args will hold Array of all arguments
end

Some more detailed information here

答案 1 :(得分:40)

splat运算符解包传递给函数的数组,以便将每个元素作为单个参数发送给函数。

一个简单的例子:

>> def func(a, b, c)
>>   puts a, b, c
>> end
=> nil

>> func(1, 2, 3)  #we can call func with three parameters
1
2
3
=> nil

>> list = [1, 2, 3]
=> [1, 2, 3]

>> func(list) #We CAN'T call func with an array, even though it has three objects
ArgumentError: 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.
1
2
3
=> nil

就是这样!

答案 2 :(得分:7)

正如大家所说,这是一个“啪啪”。寻找Ruby语法是不可能的,我在其他问题中也问过这个问题。这部分问题的答案是你在

上搜索
asterisk in ruby syntax
在Google中

。 Google会为您提供帮助,只需将您所看到的内容写入文字。

Anyhoo,就像许多Ruby代码一样,代码非常密集。

line.split(/=|;/)

生成一个SIX元素数组first_name, mickey, last_name, mouse, country, usa。然后使用splat将其变成哈希。现在Ruby人总是会发送给你看看Splat方法,因为所有内容都在Ruby中公开。我不知道它在哪里,但是一旦你有了它,你会看到它通过数组运行for并构建哈希。

您可以在core文档中查找代码。如果你找不到它(我不能),你会尝试写一些这样的代码(有效,但不是类似Ruby的代码):

line = "first_name=mickey;last_name=mouse;country=usa"
presplat = line.split(/=|;/)
splat = Hash.new
for i in (0..presplat.length-1)
    splat[presplat[i]] = presplat[i+1] if i%2==0
end

puts splat["first_name"]

然后Ruby团队将能够告诉你为什么你的代码是愚蠢的,坏的,或者只是完全错误。

如果您已经阅读过这篇文章,请仔细阅读Hash文档进行初始化。

基本上,使用多个参数初始化的哈希将它们创建为键值对:

Hash["a", 100, "b", 200] #=> {"a"=>100, "b"=>200}

因此,在您的示例中,这将导致以下Hash:

{"first_name"=>"mickey", "last_name"=>"mouse", "county"=>"usa"}