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.
Try this
Using
Enumerable#each_with_index
:As @hirolau commented,
each_with_index.map
can also be written asmap.with_index
.UPDATE
Alterantive that use
Hash#invert
:Another one:
Newer Ruby versions would allow: