Rails 3.07 dup issue

Hi not sure if this is where I should post this problem but since
upgrading to rails 3.07 dup is not working as expected for Hash

basically in method I have this
dup_row = row.dup
#then I delete a row of my original hash
row[:athlete].delete(:sports) if !row[:athlete][:sports].nil?

pretty simple but what is happening is it is deleting from the dup
and the original here is the debug
code of the original and dup just after deleting the sports

original hash values

{“athlete”=>{“first_name”=>“DaveG5600”, “gender”=>“M”,
“hometown_id”=>“40”, “birthplace_id”=>“30”, “last_name”=>“test”},
“leagues”=>{“league”=>{“id”=>“821”, “start_year”=>“1983”,
“end_year”=>“2003”}}, “clubs”=>{“club”=>[{“id”=>“11802”,
“start_year”=>nil, “end_year”=>nil}, {“id”=>“1403”, “start_year”=>nil,
“end_year”=>nil}]}, “schools”=>{“school”=>{“id”=>nil,
“start_year”=>nil, “end_year”=>nil}},
“sports”=>{“sport”=>{“id”=>“102”, “start_year”=>“1985”,
“end_year”=>“1986”, “sport_roles”=>“10”}}}}

dup row (notice sports is missing which even though I am not deleting
from this hash)
{“athlete”=>{“first_name”=>“DaveG5600”, “gender”=>“M”,
“hometown_id”=>“40”, “birthplace_id”=>“30”, “last_name”=>“test”},
“leagues”=>{“league”=>{“id”=>“821”, “start_year”=>“1983”,
“end_year”=>“2003”}}, “clubs”=>{“club”=>[{“id”=>“11802”,
“start_year”=>nil, “end_year”=>nil}, {“id”=>“1403”, “start_year”=>nil,
“end_year”=>nil}]}, “schools”=>{“school”=>{“id”=>nil,
“start_year”=>nil, “end_year”=>nil}}}}

row (this is where I expect to have the sport value deleted which is
does)
{“athlete”=>{“first_name”=>“DaveG5600”, “gender”=>“M”,
“hometown_id”=>“40”, “birthplace_id”=>“30”, “last_name”=>“test”},
“leagues”=>{“league”=>{“id”=>“821”, “start_year”=>“1983”,
“end_year”=>“2003”}}, “clubs”=>{“club”=>[{“id”=>“11802”,
“start_year”=>nil, “end_year”=>nil}, {“id”=>“1403”, “start_year”=>nil,
“end_year”=>nil}]}, “schools”=>{“school”=>{“id”=>nil,
“start_year”=>nil, “end_year”=>nil}}}}

On Jun 13, 5:21am, gerbdla [email protected] wrote:

code of the original and dup just after deleting the sports

Hash#dup does a shallow copy in ruby (ie ruby doesn’t recursively dup
the hash’s contents) - this is expected.

Fred

If you want deep copy you should use Marshal:

class Hash
def deep_dup
Marshal::load(Marshal::dump(self))
end
end

foo = {:b=>{:c=>{:d=>1}}}
bar = foo.deep_dup

foo[:b][:c][:d] = 2
p foo # => {:b=>{:c=>{:d=>2}}}
p bar # => {:b=>{:c=>{:d=>1}}}

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs