From: "Jesús Gabriel y Galán" Date: 2010-03-25T17:35:03+09:00 Subject: Re: hash problem On Thu, Mar 25, 2010 at 9:16 AM, Adam Nelreth wrote: > Hi > > I have small problem with adding data to hash table > > In loop I take some string and get IP address from it like this: > > ip = > /(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/.match(title) > > and now under ip variable I have my IP which I want to put in hash table > and count if the same IP I will find in another step (loop) > > I create hash table > test = Hash.new > and put it in table > test[ip] = 1 > > But I don't know how to search table to find if the same ip is already > in table and increase counter > > Could You tell me how to do this or give me just a clue how to figure > this out ? A typical idiom is this: irb(main):007:0> h = Hash.new(0) => {} irb(main):008:0> h["10.1.1.1"] += 1 => 1 irb(main):009:0> h["10.1.1.1"] += 1 => 2 irb(main):010:0> h["10.1.1.2"] += 1 => 1 irb(main):011:0> h["10.1.1.3"] += 1 => 1 irb(main):012:0> h => {"10.1.1.1"=>2, "10.1.1.2"=>1, "10.1.1.3"=>1} That constructor of Hash receives a default value for a non-existing key, so when you do this: h[k] += v it means h[k] = h[k] + v The right hand side h[k] evaluates to the default value if k is not in the hash, as in your case the first time you add an IP. Jesus.