From: Brian Candler Date: 2009-04-29T22:08:27+09:00 Subject: Re: Random Access using IO#pos in code blocks Arun Kumar wrote: >> freq[word] ||= [0] >> freq[word][0] += 1 >> freq[word] << f.pos << file_name >> >> > I've tried doing it but since 'freq' is a hash it gives the following > error: Show your actual code. The following code works just fine: freq = {} %w{foo bar baz bar}.each do |word| freq[word] ||= [0] freq[word][0] += 1 freq[word] << "pos" << "name" end puts freq.inspect The error suggests that you have initialized freq[word] to 0, not to [0]. 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 -- Posted via http://www.ruby-forum.com/.