'<Ruby> How can I convert "array in array" to "hash in array"? For examle, convert [["H", 3], ["S", 3], ["D", 3], ["H", 10], ["S", 4]]
I would like to convert each array in array like [["H", 3], ["S", 3], ["D", 3], ["H", 10], ["S", 4]] to hash in array such as [{"H", 3}, {"S", 3}, {"D", 3}, {"H", 10}, {"S", 4}].
This is a judgement service of Poker Hands, so same keys like H appear and I cant use Hash[suit.zip num].
If using Hash[suit.zip num], the result is {"H"=>10, "S"=>4, "D"=>5, "C"=>5}
Teach me how to solve this problem, please.
Solution 1:[1]
To convert a pair (array of 2 elements) into a one-key hash, you have to
pair = ["A", 1]
h = Hash[*pair] # This is just Hash["A", 1]
# => {"A" => 1}
now you have to map this over your original array
array = [["H", 3], ["S", 3], ["D", 3], ["H", 10], ["S", 4]]
ar_of_hashes = array.map { |pair| Hash[*pair] }
but take also in account that map and friends are able to "distribute" an item into arguments of a block, so this would also work:
array = [["H", 3], ["S", 3], ["D", 3], ["H", 10], ["S", 4]]
ar_of_hashes = array.map { |(letter, number)| {letter => number} }
this is actually taking a single parameter, that is an array of 2, and automatically taking out the items.
Finally, if a block has more than 1 argument, and the count of arguments matches the size of the iterated item as an array, then it is automatically distributed:
array = [["H", 3], ["S", 3], ["D", 3], ["H", 10], ["S", 4]]
ar_of_hashes = array.map { |letter, number| {letter => number} }
notice that now the block has 2 arguments instead of 1.
Solution 2:[2]
array = [["H", 3], ["S", 3], ["D", 3], ["H", 10], ["S", 4]]
array.map { |item| [item].to_h }
# => [{"H"=>3}, {"S"=>3}, {"D"=>3}, {"H"=>10}, {"S"=>4}]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rewritten |
| Solution 2 | Manoj Saun |
