Home > Software engineering >  <Ruby> How can I convert "array in array" to "hash in array"? For examle,
<Ruby> How can I convert "array in array" to "hash in array"? For examle,

Time:02-21

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.

CodePudding user response:

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.

CodePudding user response:

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}]
  • Related