From: Wally T Terrible Date: 2008-01-10T09:10:25+09:00 Subject: Re: About array to hash conversion I just did this myself. Because I knew how the data was stored in the array, I was able to control how I put it into the hash. What I did was this: myArray=['255','10','258','08','154','34'] #(etc) myHash={} c=0 while c<=myArray.size myHash.store(myArray[c],myArray[c+1]) c+=2 end I don't suggest that this absolutely the best way to do it, and it may not work if you don't know your data structure in the array but it was a quick and easy way for me to solve my problem. Holden Holden wrote: > Hi, > > I want to convert an array (with pairs [key,value]) to a hash. After > googling a bit I got: > > 1) Hash[*array.flatten] > > But this is not safe as Array#flatten is recursive. > > 2) array.inject({}) { |m, e| m[e[0]] = e[1]; m } > > Too ugly to consider. > > 3) Hash[*array.flatten(1)] > > That's my own attempt. It only works for Ruby > 1.9. > > But I am still wondering why... > > - Array objects have no "to_h" method? > - Hasy[*array] don't accept the [key,value] pairs (as Hash#to_a calls > return)? > > thanks, > holden >