Array to Hash

J

Josselin

is it possible to convert easily an Array like this one :

[ nil, "b", nil, nil, nil , "f", "g", nil, nil, "j"]

to an Hash like this one

{ 1 => "b", 5 => "f", 6 => "g", 9 => "j" }

where the key is the position of a value if not nil .. ?
 
W

William James

is it possible to convert easily an Array like this one :

[ nil, "b", nil, nil, nil , "f", "g", nil, nil, "j"]

to an Hash like this one

{ 1 => "b", 5 => "f", 6 => "g", 9 => "j" }

where the key is the position of a value if not nil .. ?

We don't need no stinkin' loops!
a=[ nil, "b", nil, nil, nil , "f", "g", nil, nil, "j"] => [nil, "b", nil, nil, nil, "f", "g", nil, nil, "j"]
h=Hash[*(0...a.size).zip(a).reject{|x|x[1]==nil}.flatten]
=> {5=>"f", 6=>"g", 1=>"b", 9=>"j"}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,161
Latest member
GertrudeMa
Top