From: Logan Capaldo Date: 2007-05-04T22:55:34+09:00 Subject: Re: Array to Hash ------=_Part_39846_24575367.1178286932704 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline On 5/3/07, William James wrote: > > On May 3, 11:41 am, Josselin 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"} Indeed, require 'enumerator' a.enum_with_index.reject { |v, k| v.nil? }.inject({}) { |h, (v,k)| h.update(k => v) } PS. my solution preserves nested arrays, etc. in the original dataset ------=_Part_39846_24575367.1178286932704--