From: Morton Goldberg Date: 2007-04-09T16:50:02+09:00 Subject: Re: Nesting Array loops On Apr 9, 2007, at 2:49 AM, Rubic wrote: > I new to Ruby and I have lost touch with whatever little programming I > did know a few years back. Sorry if this is a lame question. > > How does one nest arrays? > > I want to check every element of the array and compare it against rest > of the elements of that array for repeat occurences. but for now I did > be happy if I can get to even print the 2 values, hence 'puts #i, > #j' in > the code. > > > f = File.open("iplist.txt") > f1 = File.open("iplist.txt") > f.each { |i| > f1.each { |j| > puts "#{i}, #{j}" > } > } > > With the above code I only get output of one successful iteration of > f.each and it stops and doesnt continue for the rest of the values of > f.each. The problem is that both f and f1 are pointing to the same disk file. After the first iteration using f, the disk file is at EOF. When f1 attempts to iterate further, it sees the EOF and terminates. If you read the whole file into an array, your approach will work: f = File.read("/Users/mg/Desktop/test.txt") f = f.map { |e| e.chomp } # get rid on newlines puts f puts f.each do |i| f.each { |j| puts "#{i}, #{j}" } end quick fox brown fox quick, quick quick, fox quick, brown quick, fox fox, quick fox, fox fox, brown fox, fox brown, quick brown, fox brown, brown brown, fox fox, quick fox, fox fox, brown fox, fox However, to go back to your original problem of detecting duplicates, there are better ways. Here is one: # Array#uniq removes duplicates. def has_dups?(ary) ary.size != ary.uniq.size end f = File.read("/Users/mg/Desktop/test.txt") f = f.map { |e| e.chomp } # get rid on newlines has_dups?(f) # => true has_dups?(f.uniq) # => false Regards, Morton