From: Siep Korteling Date: 2008-04-25T00:39:23+09:00 Subject: Re: twolak@sktydev.com - Found word(s) list error in the Text body - Re: Hash keys Tim Wolak wrote: > (...) > Basically what I'm trying to do here is gather the account balances and > account numbers and store them in a hash and if there are accounts with > the > same number to store their balances as an array in the hash value to add > them later when I iterate over the hash. > > If there is a better way to do this that I'm not thinking of please > share > with me so I can better my ruby knowledge. > > Thanks! > Tim The following code does not store an array in a hash, it just stores a running total: DATA.gets #DATA is the stuff below __END__ #you can treat it like a file. #DATA.gets just gets the first line and ignores it. totalled = Hash.new(0) #Thanks to the (0) parameter, totalled will return 0 if a key is not found. DATA.each do |line| ar_line = line.split(",") account, balance = ar_line[0], ar_line[1].to_f totalled[account] = totalled[account] + balance #this line does the job. For the first line #read in the loop, the key "101" is not found in the hash #so it returns 0. Then the balance is added. #The key and the new (running) balance are stored. #A shorter way to write this is: #totalled[account] += balance end p totalled __END__ account,balance 101,100.00 102,500.00 101,-57.00 103,0.50 102,1 ##end code prints: {"101"=>43.0, "102"=>501.0, "103"=>0.5} If you really need the hash with an array, replace the first line with: totalled = Hash.new([]) (giving a 'default value' of an empty array); Also replace this line: totalled[account] = totalled[account] + balance with totalled[account]=totalled[account]<