问题描述
我有一个数组 X
在它值的数量。下面的阵列只有4个,但我需要code是动态的,仅具有四个数组对象不依赖。
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.
数组= [成人,家庭,单,孩子]
我想阵列
转换为一个哈希看起来像这样:
I want to convert array
to a hash that looks like this:
哈希= {0 => 成人,1 => 家庭,2 => '单',3 => '儿童'}
的哈希应该有尽可能多的键/值对作为阵列具有目的和值应在0和递增1为每个对象开始
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.
推荐答案
使用<$c$c>Enumerable#each_with_index$c$c>:
Hash[array.each_with_index.map { |value, index| [index, value] }]
# => {0=>"Adult", 1=>"Family", 2=>"Single", 3=>"Child"}
由于@hirolau评论, each_with_index.map
也可以写成 map.with_index
。
Hash[array.map.with_index { |value, index| [index, value] }]
# => {0=>"Adult", 1=>"Family", 2=>"Single", 3=>"Child"}
更新
Alterantive使用:
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"}
这篇关于数组转换为散列红宝石,而preserving数组索引值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!