From: Stefano Crocco Date: 2008-01-31T07:12:42+09:00 Subject: Re: counting the number of repititions in an array Alle Wednesday 30 January 2008, Adam Akhtar ha scritto: > Stefano Crocco wrote: > > a = [2,4,6,2,1,3,4,6,4,1,2,3,1] > > res = Hash.new(0) > > a.each do |i| > > res[i]+=1 > > end > > p res > > > > This creates a hash, which has a default value of 0 (that is, if a key > > isn't > > included in the hash, the [] method returns 0). Then, there's an > > iteration on > > all items of the array. For each element, the value of the hash item > > corresponding to the array element is increased by one. > > If the hash is empty to begin with, when you try to look up the key > using res[i] > wont it just return 0. I cant see where the hash res is assigned with > the unique values from a. writing var += something is the same as writing var = var + something In fact, ruby actually translate the first form into the second. So, when I write res[i] += 1 I mean: res[i] = res[i] + 1 When the hash is emtpy (or it doesn't contain i), the call to res[i] on the right hand gives 0, so that res[i] + 1 becomes 1. Then you have the assignment: res[i] = 1 > Also is it possible to add more keys to a hash - i checked the instance > method section in the pick axe but there was nothign like pop or push. To add a new key to a hash, you should use the []= method: hash = Hash.new #this creates an empty hash hash['a'] = 1 # sets the value corresponding to the key 'a' to 1 You need to be careful: if the hash already contained the key 'a', the previous value will be replaced by the new: hash['b'] = 2 hash['b'] = 19 puts hash['b'] => 19 Stefano