From: Robert Klemme Date: 2008-01-10T18:42:30+09:00 Subject: Re: About array to hash conversion 2008/1/10, Holden Holden : > yermej wrote: > > On Jan 9, 3:31�pm, Holden Holden wrote: > >> > >> return)? > > These would only work in one specific case. What would this do? > > > > [1, 2, 3].to_h > > That's why I prefer [key, value] pairs, to avoid any ambiguity. > > However, a theorical [1,2,3].to_h should give the same error than > Hash[*array] gives: > > irb(main):002:0> Hash[*[1,2,3]] > ArgumentError: odd number of arguments for Hash There is however one issue with a general Array to Hash conversion routine: there are different ways to convert a Hash and to me it's not clear which one should be the default. Options I can see so far: 1. if array contains pairs use them as key and value for the Hash 2. if array is flat use consecutive entries for key and value (fails with odd number of entries) 3. use indexes as keys and entries as values, e.g. ar.to_enum(:each_with_index).inject({}) {|h, (v,k)| h[k]=v;h} The last one has not been mentioned so far but there might actually be uses for this (i.e. when one wants to replace an Array with a Hash). Dunno how often this might occur though. There are probably other valid default conversion candidates, too. Kind regards robert -- use.inject do |as, often| as.you_can - without end