From: Joel VanderWerf Date: 2009-08-12T05:17:30+09:00 Subject: Re: Dynamically creating a multi dimensional hash David Sainte-claire wrote: > Hello, > > I am trying to do something that on the surface seems easy, but in > practice I don't have a clue how to approach it. I need to create a > multi-dimensional hash to represent certain attributes of a particular > item. When I hardcode the hash for testing purposes it looks something > like this: > > @skuList = [{:sku => "XXXX", :price => "$ZZZZ.ZZ"}, {:sku => "YYYY", > :price => "$AAA.AA"}] > > However, in production I need to be able to generate an almost exact > same hash dynamically, with the exception of that I don't know how many > objects will need to be inserted into the hash. > > Basically, I will be reading in a file that contains an unknown number > of item names and need to return hash that contains the above > attributes for all entries in the file that I just read. > > Unfortunately, I am very new to Ruby, and don't have a clue where to > start on something like this. > > Can someone help me out? > > Thanks, > David Looks like an array of hashes. What do you mean by "multidimensional hash"? There's a ruby idiom that may or may not apply here, making use of the default proc of a hash to create arbitrary nesting: make_hash = proc do |hash,key| hash[key] = Hash.new(&make_hash) end h = Hash.new(&make_hash) h[1][2][3] = "foo" p h # => {1=>{2=>{3=>"foo"}}} But if you are just trying to construct an array of hashes, something like this may work: ary = [] File.open(...).each do |line| hash = your_parser(line) ary << hash end Sorry if I've misunderstood! -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407