Making a Hash from an array - how does this work?
Asked Answered
S

2

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

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

Why does the splat cause the array to be so neatly parsed into the 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 at consecutive positions in the fruit array?

Does it matter that the splat is used here? Can a Hash not define itself from an arry so directly otherwise?

Smarmy answered 22/9, 2009 at 4:23 Comment(0)
S
10

As the documentation states:

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 can't pass an array to the Hash[] method according documentation, thus the splat is just a way to explode the fruit array and pass its elements as normal arguments to the Hash[] method. Indeed this is a very common use of the splat operator.

The cool thing is that if you try to pass an odd number of arguments to Hash 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
Slippage answered 22/9, 2009 at 4:37 Comment(0)
R
2

Look at the public class method [] in class Hash. (Say, over here.) It clearly states that a new Hash (instance) will be created and populated with the given objects. Naturally, they occur in pairs. The splat operator essentially expands an array when used as a parameter.

Rosalynrosalynd answered 22/9, 2009 at 4:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.