fruit = ["apple","red","banana","yellow"]
=> ["apple", "red", "banana", "yellow"]
Hash[*fruit]
=> {"apple"=>"red", "banana"=>"yellow"}
Run Code Online (Sandbox Code Playgroud)
为什么splat导致数组被如此整齐地解析为Hash?
或者,更确切地说,哈希如何"知道""苹果"是关键而"红色"是它的对应值?
是因为它们在水果阵列中处于连续位置吗?
在这里使用splat是否重要?哈希不能直接从arry定义自己吗?
khe*_*lll 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}
Run Code Online (Sandbox Code Playgroud)
不能传递数组添加到Hash[]根据方法的文档,因此,图示只是为了一个方式爆炸的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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4880 次 |
| 最近记录: |