From: neubyr Date: 2011-04-23T10:40:44+09:00 Subject: Re: using hash keys as object name Thanks a lot for explaining the basics.. Changed the implementation. -- neuby On 4/21/11, Robert Klemme wrote: > On Wed, Apr 20, 2011 at 11:19 PM, neubyr wrote: >> Thanks for the help Robert. Following is a scenario I am trying to >> implement: >> I want to create File objects based on a hash. The 'fruits' hash will >> be created based on user input (yaml file), so I don't know how long >> the hash will be beforehand. For each key in this hash I would like to >> instantiate a File object with object/var name same as hash key. In >> future I may have a subclass of File class say UserFile class. The >> UserFile objects will be instantiated in a similar manner as File >> object, in addition they will get hash values passed on as variables. > > There is no need to create local variables for these File objects - in > fact, it won't work. You rather want to create a second Hash. > > FileData = Struct.new :io, :attributes > > user_input = { ... } # from YAML > > files = {} > > user_input.each do |k,v| > files[k] = FileData.new File.open(k), v # whatever else > end > > # use files > ... > > # close files > files.each do |k,v| > v.io.close > end > > Note, I deliberately left out error handling in order to keep the code > simple. > > Kind regards > > robert > > -- > remember.guy do |as, often| as.you_can - without end > http://blog.rubybestpractices.com/ > >