Bugs item #10538, was opened at 2007-05-03 02:17 You can respond by visiting: http://rubyforge.org/tracker/?func=detail&atid=1698&aid=10538&group_id=426 Category: Core Group: 1.8.5 Status: Open Resolution: None Priority: 3 Submitted By: Carl Graff (cgramona2) Assigned to: Nobody (None) Summary: sub! causing unexpected side effect Initial Comment: I have a section of code that behaves unexpectedly in my opinion. First the section of code: def adjust_bol_row(bol_row, hist_bol_row, change_disp = true) adj_bol_row = bol_row.dup adj_bol_row['DISPOSITION'] = 'ADD' if change_disp adj_bol_row['SHIPMENT_PRI_REF'].sub!(/-..-/,hist_bol_row['SHIPMENT_PRI_REF'][/-..-/]) if hist_bol_row return adj_bol_row end The statement: adj_bol_row['SHIPMENT_PRI_REF'].sub!(/-..-/,hist_bol_row['SHIPMENT_PRI_REF'][/-..-/]) if hist_bol_row Causes adj_bol_row['SHIPMENT_PRI_REF'] to get updated as expected BUT has the side affect of updating bol_row['SHIPMENT_PRI_REF'] When I use this code def adjust_bol_row(bol_row, hist_bol_row, change_disp = true) adj_bol_row = bol_row.dup adj_bol_row['DISPOSITION'] = 'ADD' if change_disp adj_bol_row['SHIPMENT_PRI_REF'] = adj_bol_row['SHIPMENT_PRI_REF'].sub(/-..-/,hist_bol_row['SHIPMENT_PRI_REF'][/-..-/]) if hist_bol_row return adj_bol_row end Only hash element adj_bol_row['SHIPMENT_PRI_REF'] gets updated as I expect. Why would sub! in this case cause another hash to get updated? Thanks, Carl ---------------------------------------------------------------------- >Comment By: Carl Graff (cgramona2) Date: 2007-05-03 14:46 Message: Hmmm... I do understand your explanation but in that case shouldn't both sections of code update both adj_bol_row ['SHIPMENT_PRI_REF'] and bol_row['SHIPMENT_PRI_REF']? I will test sub and sub! in your example and see if I modify h1[4] then h0[4] a;slo gets modified. Also is there an easy way to "clone" the hash elements of one hash as NEW objects in another hash to avoid this issue altogether? Thanks, Carl ---------------------------------------------------------------------- Comment By: Sam Roberts (sam) Date: 2007-05-03 04:07 Message: You duplicated the hash, you didn't duplicate the values in the hash. Use .id or .object_id to see this: ensemble:~ % irb irb(main):001:0> s = "hi\n" => "hi\n" irb(main):002:0> h0={4=>s} => {4=>"hi\n"} irb(main):003:0> h1=h0.dup => {4=>"hi\n"} irb(main):005:0> s.id => 371264 irb(main):006:0> h0[4].id => 371264 irb(main):007:0> h1[4].id => 371264 irb(main):008:0> Its the same string. ---------------------------------------------------------------------- You can respond by visiting: http://rubyforge.org/tracker/?func=detail&atid=1698&aid=10538&group_id=426