Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Array to Hash while preserving Array index values in Ruby

Tags:

arrays

ruby

hash

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.

like image 957
Luigi Avatar asked Oct 12 '13 04:10

Luigi


1 Answers

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"}
like image 86
falsetru Avatar answered Oct 15 '22 17:10

falsetru