5
fruit = ["apple","red","banana","yellow"]
=> ["apple", "red", "banana", "yellow"]

Hash[*fruit]    
=> {"apple"=>"red", "banana"=>"yellow"}

为什么 splat 会导致数组被如此整齐地解析为 Hash?

或者,更准确地说,哈希是如何“知道”“apple”是键而“red”是其对应的值?

仅仅是因为它们在水果数组中的连续位置吗?

在这里使用 splat 是否重要?哈希不能直接从数组中定义自己吗?

4

2 回答 2

10

正如文档所述:

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

根据文档,您不能将数组传递给Hash[]方法,因此 splat 只是一种爆炸fruit​​数组并将其元素作为普通参数传递给方法的方法Hash[]。事实上,这是 splat 运算符的一个非常常见的用法。

很酷的事情是,如果你尝试向 Hash 传递奇数个参数,你会得到一个ArgumentError异常:

fruit = ["apple","red","banana","yellow","orange"]
#=> ["apple", "red", "banana", "yellow", "orange"]
Hash[*fruit] #=> ArgumentError: odd number of arguments for Hash
于 2009-09-22T04:37:15.107 回答
2

查看[]类Hash中的公共类方法。(比如说,在这里。)它清楚地表明将创建一个新的哈希(实例)并用给定的对象填充。自然地,它们成对出现。splat 运算符在用作参数时实质上扩展了一个数组。

于 2009-09-22T04:37:47.430 回答