From: Daniel Schierbeck Date: 2006-06-20T05:35:41+09:00 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