From: Matthew Smillie Date: 2006-06-20T05:50:30+09:00 Subject: Re: associative array naming indirection On Jun 19, 2006, at 20:51, 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 > > -------------- > > obviously, some giant conceptual leap needs to be made, or its a > miniscule typo. (methinks the former) It's the typos, I'm afraid. First, you've got an unterminated string literal on 'district'. Second you're using the wrong syntax for hash assignment, the => notation is used for hash literal values. It should look like this: @pageData["something"] = "something else" There's also no reason to use #upto here - check the docs for Array and Enumerable, there are lots of methods which don't require you to fiddle with finding sizes and the associated potential of fencepost errors. I'd do this, if it were me: def add_data(data) @page_data[*@labels.zip(data).flatten] end Basically, zip combines the two arrays to something like this: [['a', 1], ['b', 2]], flatten changes this to ['a', 1, 'b', 2], and the * transforms that from an array to a list (of arguments) to the Hash#[] method, which creates a new hash from that list of arguments. matthew smillie. docs for Array: http://ruby-doc.org/core/classes/Array.html docs for Enumerable: http://ruby-doc.org/core/classes/Enumerable.html docs for Hash: http://ruby-doc.org/core/classes/Hash.html