我有一个数组:
arr = ["a", "b", "c"]
我想要做的是创建一个哈希,使其看起来像:
{1 => "a", 2 => "b", 3 => c}
我试图这样做:
Hash[arr.each_with_index.map { |item, i| [i => item] }]
但没有得到我要找的东西。
我有一个数组:
arr = ["a", "b", "c"]
我想要做的是创建一个哈希,使其看起来像:
{1 => "a", 2 => "b", 3 => c}
我试图这样做:
Hash[arr.each_with_index.map { |item, i| [i => item] }]
但没有得到我要找的东西。
each_with_index
返回原始接收者。为了得到与原始接收器不同的东西,map
无论如何都是必要的。所以不需要额外的步骤使用each
or each_with_index
。此外,with_index
可选地采用初始索引。
Hash[arr.map.with_index(1){|item, i| [i, item]}]
# => {1 => "a", 2 => "b", 3 => c}
Hash[]
将数组数组作为参数。所以你需要使用[i, item]
而不是[i => item]
arr = ["a", "b", "c"]
Hash[arr.each_with_index.map{|item, i| [i+1, item] }]
#=> {1=>"a", 2=>"b", 3=>"c"}
只是为了澄清:[i => item]
与写作相同,[{i => item}]
因此您实际上生成了一个数组数组,每个数组又包含一个哈希。
我还在+1
索引中添加了一个,以便哈希键1
按照您的要求开始。如果您不在乎,或者您想从 开始0
,请不要使用它。
arr = ["a", "b", "c"]
p Hash[arr.map.with_index(1){|i,j| [j,i]}]
# >> {1=>"a", 2=>"b", 3=>"c"}