I have an array that has X
number of values in it. The following array only has 4, but I need the code to be dynamic and not reliant on only having four array objects.
array = ["Adult", "Family", "Single", "Child"]
I want to convert array
to a hash that looks like this:
hash = {0 => 'Adult', 1 => 'Family', 2 => 'Single', 3 => 'Child'}
The hash should have as many key/value pairs as the array has objects, and the values should start at 0 and increment by 1 for each object.
Using Enumerable#each_with_index
:
Hash[array.each_with_index.map { |value, index| [index, value] }]
# => {0=>"Adult", 1=>"Family", 2=>"Single", 3=>"Child"}
As @hirolau commented, each_with_index.map
can also be written as map.with_index
.
Hash[array.map.with_index { |value, index| [index, value] }]
# => {0=>"Adult", 1=>"Family", 2=>"Single", 3=>"Child"}
UPDATE
Alterantive that use Hash#invert
:
Hash[array.map.with_index{|*x|x}].invert
# => {0=>"Adult", 1=>"Family", 2=>"Single", 3=>"Child"}
Hash[[*array.map.with_index]].invert
# => {0=>"Adult", 1=>"Family", 2=>"Single", 3=>"Child"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With