[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Array to Hash

Josselin

5/3/2007 4:42:00 PM

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 .. ?

1 Answer

William James

5/3/2007 7:45:00 PM

0

On May 3, 11:41 am, Josselin <josse...@wanadoo.fr> wrote:
> 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"}