Creating a hash from an array - how does it work?
fruit = ["apple","red","banana","yellow"] => ["apple", "red", "banana", "yellow"] Hash[*fruit] => {"apple"=>"red", "banana"=>"yellow"} Why does splat make an array so neatly understand Hash?
Or, more precisely, how does the hash βknowβ that βappleβ is the key, and βredβ is its corresponding value?
Is it simply because they are in consecutive positions in the fruit array?
Does splat use here? Can a hash not define itself from arry so directly differently?
As the documentation reports:
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} You cannot pass an array to the Hash[] method according to the documentation, so splat is just a way to explode the fruit array and pass its elements as normal arguments to Hash[] . Indeed, this is a very common use of the splat operator.
The most interesting thing is that if you try to pass an odd number of Hash arguments, you will get an ArgumentError exception:
fruit = ["apple","red","banana","yellow","orange"] #=> ["apple", "red", "banana", "yellow", "orange"] Hash[*fruit] #=> ArgumentError: odd number of arguments for Hash