Convert Array to Hash while preserving Array index

2019-02-04 15:28发布

问题:

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.

回答1:

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"}


回答2:

Another one:

Hash[array.each_index.zip(array)]
#=> {0=>"Adult", 1=>"Family", 2=>"Single", 3=>"Child"}

Newer Ruby versions would allow:

array.each_with_index.to_h.invert
#=> {0=>"Adult", 1=>"Family", 2=>"Single", 3=>"Child"}


回答3:

  Hash[*(0..array.size-1).to_a.zip(array)]
    => {0=>"Adult", 1=>"Family", 2=>"Single", 3=>"Child"} 


回答4:

Try this

array.each_with_index.inject({}){ |hash, (val, i)| hash[i]=val; hash }
=> {0=>"Adult", 1=>"Family", 2=>"Single", 3=>"Child"} 


标签: ruby arrays hash