From: Robert Klemme Date: 2004-04-24T18:24:06+09:00 Subject: Re: Array to Hash "Mark Hubbart" schrieb im Newsbeitrag news:36BA84AE-95B4-11D8-9D1D-000502FDD5CC@mac.com... > > On Apr 23, 2004, at 10:14 PM, Ara.T.Howard wrote: > > > On Sat, 24 Apr 2004 nobu.nokada@softhome.net wrote: > > > >> Hi, > >> > >> At Sat, 24 Apr 2004 13:05:20 +0900, > >> Pe�a, Botp wrote in [ruby-talk:98203]: > >>> I would rather prefer: > >>> > >>>>> h2 = a.to_hash # or a.to_h > >>> {"x"=>1, "y"=>3} > >> > >> module Enumerable > >> def to_h > >> inject({}) {|h, (k, v)| h[k] = v; h} > > ^^^^^^ > > ^^^^^^ > > ^^^^^^ > > what's this? > >> end > >> end > > module Enumerable > def to_h > inject({}) {|h, (k, v)| h[k] = v; h} > ^ ^^^^ > 1 2 > 1: is the hash that keeps being passed through inject each time. > 2: is the key=>value pair, expanding it from a two element array. > > I didn't even realize you could do that type of assignment in a block's > parameter list, but hey! that's pretty cool. > > I think this should be a standard Array method. There have been many > times I've done just this type of thing to get a hash from an array, > for various reasons. 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? robert