From: Yossef Mendelssohn Date: 2008-05-14T00:14:01+09:00 Subject: Re: hash merge On May 13, 9:48 am, Tim Wolak wrote: > I'm not sure if I'm using this the right way and I'm hoping you guys can > help. > > I am merging two hashes together using merge and need to keep the keys > the same and subtract the difference between the two values. The keys > are account numbers and the values are the balances. Not sure why the > balances are not subtracting and creating the new value. > > Thanks in advance. > Tim > > 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 > -- > Posted viahttp://www.ruby-forum.com/. I'm not finding that to be the case. >> a = {:a => 1, :b => 2} => {:a=>1, :b=>2} >> b = {:b => 0, :c => 3} => {:c=>3, :b=>0} >> a.merge b => {:c=>3, :a=>1, :b=>0} >> a.merge(b) { |key, old, new| old - new } => {:c=>3, :a=>1, :b=>2} and with your code: >> 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 => nil >> c = Calculate.new(a, b) => #3, :b=>0}, @sktyfuta={:b=>2, :a=>1}> >> c.data_comp => {:c=>3, :a=>1, :b=>2} Thanks for teaching me about Hash#merge with a block, by the way. -- -yossef