如何将数组["a","b","c","d"]
转换为哈希,其中键等于数组索引+ 1. {1 => "a", 2 => "b", 3 => "c", 4 => "d"}
答案 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"}