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"}
2 Answers
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"}
2 Comments
Ajedi32
Oh, nice! I was going to suggest
["a","b","c","d"].each.with_index(1).to_a.map(&:reverse).to_h or something, but this is much cleaner.Arup Rakshit
@Ajedi32 Another was
a.each_index.with_object({}) { |i, h| h[i+1] = a[i] }... :D