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

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?

+4
source share
2 answers

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 
+9
source

Look at the open class method [] in the Hash class. (Let's say here.) It clearly states that a new Hash (instance) will be created and populated with these objects. Naturally, they are found in pairs. The splat operator significantly expands the array when used as a parameter.

+2
source

All Articles