From: Wilson Bilkovich Date: 2005-12-31T07:34:40+09:00 Subject: Re: Another Newb asks questions. On 12/30/05, Joseph Divelbiss wrote: > Ok, recently started "trying" to learn this wonderful language, but am > experiencing major problems with a section of code that I think "should" > work.. and my brain is so convinced that I did it correctly that I can't > see some obvious error. Ive isolated the problem to this single section > of code.. what do you all think? > > > #This section reads data files and saves odd lines as the key, even > lines as the value for a hash. > > if Dir["/Program Files/.../data/"].last != nil > script_data_dir = "/Program Files/.../data/" > end > build_hash = Proc.new do |type| > hash.new = type_hash > file.open("#{script_data_dir}type.dat", "r") { |file| > data = file.readlines > data.delete_if { |line| line.chomp.empty? } > until data.empty? > $type_hash[data.shift.chomp] = data.shift.chomp > end > } > end > build_hash.call(test) > end > This solution uses the 'enumerator' module, included in the standard library. require 'enumerator' Dir.chdir(script_data_dir) type_hash = Hash.new File.open('type.dat','r') do |file| file.each_slice(2) do |odd, even| type_hash[odd.chomp] = even.chomp end end each_slice(2) is taking each pair of lines in the file, and passing them to the block. So, [line1, line2], then [line3, line4], etc, etc. You should probably also have a check in there to make sure the file has an even number of lines. You can also use File.exists?() to check for the presence of a directory. abort "Oh no!" unless File.exists?("C:/Program Files/something/data_dir")