From: Brian Candler Date: 2009-04-29T18:40:35+09:00 Subject: Re: Random Access using IO#pos in code blocks Arun Kumar wrote: > unless freq.has_key?(word) > freq[word] = [1,f.pos,file_name] # freq is a hash, that > stores an array containing index, position of word (THE PROBLEM).. > else > freq[word].to_a[0] += 1 > freq[word].to_a<< f.pos << file_name > end BTW, you can replace all that by: freq[word] ||= [0] freq[word][0] += 1 freq[word] << f.pos << file_name As for the pos, since you've already slurped in the data you'll need to remember where you are within your buffer. Your outer loop could become something like this: para_pos = 0 f.readlines("\r\n\r\n").each do |para| ... para_pos += para.size + 4 end Unfortunately, I don't think string#scan will give you offsets into the strings found. In ruby 1.8 you can write this: pos = 0 while md = /\b\w+\b/.match(para[pos..-1]) word = md[0] puts "Match #{word} at #{para_pos+pos+md.begin(0)}" pos += md.end(0) ... end In ruby 1.9 (but not 1.8.6/1.8.7), Regexp.match takes a start pos, so you could optimise it to this: pos = 0 while md = /\b\w+\b/.match(para, pos) word = md[0] puts "Match #{word} at #{para_pos+md.begin(0)}" pos = md.end(0) ... end However in ruby 1.9 the offsets used will be in terms of number of characters, not number of bytes. It would be up to you to convert this back into byte offsets into the file, if that's what you're after. -- Posted via http://www.ruby-forum.com/.