From: Todd Benson Date: 2008-05-15T03:00:47+09:00 Subject: Re: changing hash key On Wed, May 14, 2008 at 11:53 AM, Tim Wolak wrote: > Hmm ok then maybe changing the keys is not what I need to do then. > > The reason I have skty and sktyny is that those are account names, sorry > should have stated that earlier. So I have a list of account numbers > and their balances, all accounts listed 500 through 539 should have a > key of skty and accounts with 540 through 550 should be sktyny. All the > account balances for skty should be combined into the value for skty > and all the balances should be combined for teh value of sktyny. Here > is the full code, I did not want to post a mile long request with it > all in there. > > Tim > > > > class SktyFut > attr_reader :acct > > def initialize(filename) > @acct = File.new(filename, "r") I'm not sure ruby automagically closes the file when the instance of SktyFut is garbage collected. You open a file and assign it to a class instance variable. Looks a little scary to me. > end > > def future_data > @sktylist = Hash.new(0) > @acct.each do |list| > office = list[21..23] > if office == "RPT" > next > else > acctnum = list[24..28] > end > lv = list[217..230] > is_negative = list[215,1] == "-" > value = lv.to_f/100 > value = -value if is_negative value = list[215..230].delete(' ').to_f/100 # if the character separating - from lv is a space > > # Add vales to hash > > @sktylist[acctnum] += value > end > return @sktylist > end > end > > class Calculate > attr_reader :sktyfuta, :sktyfutb > def initialize(sktyfuta, sktyfutb) > @sktyfuta = sktyfuta > @sktyfutb = sktyfutb > end > > def data_comp > @sktyfuta.merge(@sktyfutb) { |key, old_value, > new_value| old_value - new_value } > end > #end > end > > class FinalNum > attr_reader :sktynl > def initialize(sktynl) > @sktynl = sktynl > end > > def numbers > @skty = Hash.new(0) > @sktynl.each do |key, value| > if key <= "539" > key.to_s > key = "SKTY" > @skty[key] += value replace above 3 lines with... @skty["SKTY"] += value > elsif key >="540" > key = "SKYNY" > @skty[key] += value replace above 3 lines with... @skty["SKYNY"] += value or SKTYNY or whatever it is you are using > end > #@skty.each{ |key, value| puts "#{key} value > #{value}" } > Here should be... return @skty > end > end > end > > Dir.chdir("/tmp") > post = SktyFut.new("SKTYFutBal20080513.txt") > a = post.future_data > #a.each{|key, value| puts "#{key} value is #{value}"} > pre = SktyFut.new("SKTYFutBal20080512.txt") > b = pre.future_data > data = Calculate.new(a,b) > iteration = data.data_comp > iteration.sort > #iteration.each{|key, value| puts "#{key} comp equals #{value}" } > sktyfinal = FinalNum.new(iteration) > submission = sktyfinal.numbers > submission.each{ |key, value| puts "#{key} line is #{value}" } For the #numbers method, you might someday want to check out #select. For example. skny_sum = @sktynl.select {|k, v| k < 540}.inject(0) {|sum, arr| sum + arr[1]} hth, Todd