From: Rob Biedenharn Date: 2010-03-25T21:10:57+09:00 Subject: Re: hash problem On Mar 25, 2010, at 6:16 AM, Adam Nelreth wrote: > Ok - here is code: > > login = 'aaa' > test = Hash.new You can still simplify this with the suggestion that you received from several others. Initialize your hash as: test = Hash.new(0) So that missing keys will appear as 0. (see note at end, too) > > imap = Net::IMAP.new('imap-server',993,true) > puts "passwd: " > pass = gets.chop > imap.login(login,pass) > imap.select('example') > imap.uid_search(["SUBJECT", "To-check", > "NOT", "SEEN"]).each do |uid| > mess = imap.uid_fetch(uid, "ENVELOPE")[0].attr["ENVELOPE"] > title = mess.subject > 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) > if test.has_key?(ip) > test[ip] += 1 > else > test[ip] = 1 > end Then you don't need to have this if, just put: (including where Robert pointed out that ip holds a MatchData object. test[ip[0]] += 1 Which is syntactic sugar for: test[ip[0]] = test[ip[0]] + 1 If that key (ip[0]) doesn't exist, it behaves like test[ip[0]] = 0 + 1 > end > imap.logout() > imap.disconnect() > > I try with else test[ip] = 1 and without else - it still doesn't work > like I need - maybe there is problem with "" or '' because I don't set > it when I put key to hash table > -- > Posted via http://www.ruby-forum.com/. > -Rob *Note: In general, if you want to set up a hash this way, you might need to specifically assign to the hash like: test = Hash.new {|h,k| h[k] = 0 } but a Fixnum is immutable so there's no problem "sharing" the value 0. If you were adding to an Array, these two initializations would lead to different results: test = Hash.new([]) test = Hash.new {|h,k| h[k] = [] } (What those results *are* is left as an exercise for the reader ;-) Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com