sabrams
sabrams

Reputation: 1128

Ruby convert array to hash using array index as keys

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

Answers (2)

Arup Rakshit
Arup Rakshit

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

sawa
sawa

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

Related Questions