From: ara.t.howard@... Date: 2006-03-01T11:39:57+09:00 Subject: Re: Hash.from_zipped_array On Wed, 1 Mar 2006, Farrel Lifson wrote: > Hi folks, > > Array has got a pretty cool method zip which 'zips' two arrays together like so: > > [1,2,3].zip([2,4,6]) > => [[1,2],[2,4],[3,6]] > > That's also what you get when you call to_a on a Hash like > {1=>2,2=>4,3=>6}, so I thought why not add a method to Hash to do the > reverse, that is to construct a Hash from a zipped array? > > class Hash > def Hash.from_zipped_array(zipped_array) > zipped_array.inject({}) do |hash,key_value_pair| > hash[key_value_pair[0]] =key_value_pair[1] > hash > end > end > end > > # Example usage > animal = ["dog","cat",bird"] > sound = ["woof,"meow","cheep"] > > make_a_sound_like_a = Hash.from_zipped_array(animal.zip(sound) > make_a_sound_like_a["dog"] > =>"woof" > > Useful enough for inclusion? > > Farrel it's pretty dang easy to do already: harp:~ > cat a.rb animal, sound = %w[dog cat bird], %w[woof meow cheep] require 'yaml' and y Hash[*animal.zip(sound).flatten] harp:~ > ruby a.rb --- cat: meow bird: cheep dog: woof kind regards. -a -- judge your success by what you had to give up in order to get it. - h.h. the 14th dali lama