Convert Array to Hash while preserving Array index

2019-02-04 15:27发布

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.

标签: ruby arrays hash
4条回答
我命由我不由天
2楼-- · 2019-02-04 15:56

Try this

array.each_with_index.inject({}){ |hash, (val, i)| hash[i]=val; hash }
=> {0=>"Adult", 1=>"Family", 2=>"Single", 3=>"Child"} 
查看更多
Animai°情兽
3楼-- · 2019-02-04 16:02

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"}
查看更多
虎瘦雄心在
4楼-- · 2019-02-04 16:12
  Hash[*(0..array.size-1).to_a.zip(array)]
    => {0=>"Adult", 1=>"Family", 2=>"Single", 3=>"Child"} 
查看更多
倾城 Initia
5楼-- · 2019-02-04 16:13

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"}
查看更多
登录 后发表回答