Ruby使用数组索引作为键将数组转换为哈希

时间:2015-03-27 12:50:08

标签: ruby

如何将数组["a","b","c","d"]转换为哈希,其中键等于数组索引+ 1. {1 => "a", 2 => "b", 3 => "c", 4 => "d"}

2 个答案:

答案 0 :(得分:5)

这是我的工作:

(1..a.size).zip(a)
# => [[1, "a"], [2, "b"], [3, "c"], [4, "d"]]
(1..a.size).zip(a).to_h
# => {1=>"a", 2=>"b", 3=>"c", 4=>"d"}

答案 1 :(得分:3)

["a","b","c","d"]
.each.with_index(1).with_object({}){|(e, i), h| h[i] = e}
# => {1=>"a", 2=>"b", 3=>"c", 4=>"d"}