From: Brian Candler Date: 2009-01-15T18:30:34+09:00 Subject: Re: undefined method `[]' for nil:NilClass - how to prevent? Mmcolli00 Mom wrote: > #Searches through a text file and, at one row at a time, counts how many > occurrences of the value exist for the column. For instance, if word, > 'bird' exists in column1 row1 then count how many birds exist for the > whole column. Next..count the occurrences of bird in the column 2. If > the numbers do not match then outputs "Value does not contain a match:" > +Value. --- Here's a simple version count1 = Hash.new(0) # word => count in col1 count2 = Hash.new(0) # word => count in col2 File.open("temp.txt") do |src| src.each_line do |line| word1, word2 = line.chomp.split(",") count1[word1] += 1 count2[word2] += 1 end end words = (count1.keys + count2.keys).uniq words.each do |word| if count1[word] != count2[word] puts "Value does not contain a match: #{word}" end end --- However you can remove some duplication by choice --- of a suitable data structure: a single hash which maps --- to an array giving the counts in col1 and col2 # word => [col1_count, col2_count] counts = Hash.new { |h,k| h[k] = Array.new(2,0) } File.open("temp.txt") do |src| src.each_line do |line| line.chomp.split(",").each_with_index do |word, i| counts[word][i] += 1 end end end counts.each do |word, cols| if cols.uniq.size != 1 puts "Word #{word.inspect} occurs different times: #{cols.inspect}" end end -- Posted via http://www.ruby-forum.com/.