From: Daniel Schierbeck Date: 2006-06-20T17:49:34+09:00 Subject: Re: associative array naming indirection Berger, Daniel wrote: >> -----Original Message----- >> From: Daniel Schierbeck [mailto:daniel.schierbeck@gmail.com] >> Sent: Monday, June 19, 2006 2:36 PM >> To: ruby-talk ML >> Subject: Re: associative array naming indirection >> >> >> dan donaldson wrote: >>> I have an array of names in string form as an instance var. >> The class >>> the array is in has a method that takes an array of string values. >>> >>> I want to construct an associative array such that the names in the >>> first array are the keys to the values in the received array. >>> >>> this throws an error: >>> -------------- >>> def initialize >>> @labels = ['prov', 'area', 'zone', district', 'postalcode', >>> 'city_prov', 'addr'] >>> @pageData = {} >>> end >>> >>> def adddata(data) >>> max = data.length >>> max -= 1 >>> 0.upto(max) {|i| @pageData[@labels[i]] => data[i] } >>> end >> def add_data(data) >> Hash[*@labels.zip(data).flatten] >> end >> >> Hash.[] takes an argument list with the even items being the keys and >> the odd items the values of the hash, i.e. >> >> Hash[:a, 1, :b, 2, :c, 3] => {:a => 1, :b => 2, :c => 3} >> >> The asterisk turns an array into an argument list, i.e. >> >> foo(*[:a, :b, :c]) >> >> is the same as >> >> foo(:a, :b, :c) >> >> You can read about Array#zip and Array#flatten on the documentation >> pages, or by using ri from the terminal, e.g. >> >> $ ri Array#zip >> >> >> Cheers, >> Daniel > > The above works great if you're limited to the standard library. > However, if you're allowed to use third party packages, I prefer hash > slices for this sort of thing: > > require 'hashslice' > > def adddata(*data) > @pageData[*@labels] = *data > end > > IMHO this behavior should exist in the current Hash class. :) I agree, and I'm using it myself. I just usually try to limit myself to the standard library when answering questions on this list, to minimize the hazzle the user has to go through. Cheers, Daniel