From: Robert Klemme Date: 2009-04-30T00:45:51+09:00 Subject: Re: Random Access using IO#pos in code blocks 2009/4/29 Arun Kumar : >> >> >> Or perhaps you set freq = Hash.new(0), which is wrong in this case, >> because the default element needs to be [0] not 0. >> >> An alternative is to auto-initialize each hash element like this: >> >> freq = Hash.new { |h,k| h[k] = [0] } >> %w{foo bar baz bar}.each do |word| >>  freq[word][0] += 1 >>  freq[word] << "pos" << "name" >> end >> puts freq.inspect This is a typical case where I would introduce a separate class or even multiple classes because it makes life so much more readable. WordPositon = Struct.new :file, :pos WordStats = Struct.new :word, :positions do def count; positions.size; end end freq = Hash.new {|h,word| h[word.freeze] = WordStat.new(word, [])} ... freq[word].positions << WordPosition.new(file_name, pos) ... Then you can do freq.sort_by {|w,stat| stat.count} Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/