From: Mark Hubbart Date: 2004-04-24T19:22:08+09:00 Subject: Re: Array to Hash On Apr 24, 2004, at 2:54 AM, Pe�a, Botp wrote: > > Robert Klemme [mailto:bob.news@gmx.net] wrote: > >> There's one reason why this may not be a standard method: >> there are at least two equally reasonable representations of >> a mapping stored in an array: >> >> Nested arrays as returned by Hash#to_a: [[key1, val1], [key2, val2]] >> >> A sequence: [key1, val1, key2, val2] as used by Hash[] >> >> Obviously there is no simple way from a Hash to an Array and >> back to a Hash. >> (Btw: is that ever needed? I mean, if you have a hash you can >> easily create a copy without an intermediate array.) >> >> So the question is wich representation Enumerable#to_h should >> expect - nested or sequence? > > I am concerned more on the language. > > Which would you prefer? > > Hash#to_a or Hash[*mumblearray.flatten] > > IMHO, I prefer the first; more rubyish. The second looks weird, and my > brain > aches just to remember it. > > Now, since the first notation returns an array of pairs, then _it_ is > in > consonance with the hash notation (since hashes are pairs too). Ergo, > to > answer your question, I choose the nested. > > Ok, now I have a question for you robert (since you're one of the ruby > gurus > here), Is it possible for #to_h to determine if the array is nested or > not, > and then adjust accordingly? Well, I'm not robert :) but here's one way to check. If the array consists of objects that respond to #size and #inject, and #size returns 2, it is assumed that this is a nested array. Otherwise, it runs it through the Hash[obj] thing. class Array def to_h if all?{|e| e.respond_to?(:size, :inject) and e.size == 2} inject({}){|h,(k,v)| h[k] = v; h} else Hash[*self] end end end --Mark >> robert > > kind regards -botp >