2

我有一个数组:

arr = ["a", "b", "c"]

我想要做的是创建一个哈希,使其看起来像:

{1 => "a", 2 => "b", 3 => c}

我试图这样做:

Hash[arr.each_with_index.map { |item, i|  [i => item] }]

但没有得到我要找的东西。

4

3 回答 3

3

each_with_index返回原始接收者。为了得到与原始接收器不同的东西,map无论如何都是必要的。所以不需要额外的步骤使用eachor each_with_index。此外,with_index可选地采用初始索引。

Hash[arr.map.with_index(1){|item, i| [i, item]}]
# => {1 => "a", 2 => "b", 3 => c}
于 2013-07-17T08:36:33.217 回答
1

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,请不要使用它。

于 2013-07-17T08:41:00.560 回答
0
arr = ["a", "b", "c"]
p Hash[arr.map.with_index(1){|i,j| [j,i]}]
# >> {1=>"a", 2=>"b", 3=>"c"}
于 2013-07-17T08:41:21.707 回答