Reputation: 1128
How can I transform the array ["a","b","c","d"]
into a hash where the key equals the array index + 1. {1 => "a", 2 => "b", 3 => "c", 4 => "d"}
Upvotes: 0
Views: 326
Reputation: 118271
Here is my work :
(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"}
Upvotes: 5
Reputation: 168131
["a","b","c","d"]
.each.with_index(1).with_object({}){|(e, i), h| h[i] = e}
# => {1=>"a", 2=>"b", 3=>"c", 4=>"d"}
Upvotes: 3