hash - for each loop in hashes in ruby? -


i'm new in ruby i'm learning hashes , below code behaving hell please

hash = {"15" => {:a=>"a_15", :b=>"b_15", :c=>"c_15 ", :d=>"pass"},         "16" => {:a=>"d_16", :b=>"e_16", :c=>"f_16 ", :d=>"fail"}}    mod= {} h = {} hash.each |k,v|   v.each |x,y|     mod[x] = y   end   h[k] = mod   # mod={}    # don't want use technique                # creates new object not required end  p h 

expected output:

{"15" => {:a=>"a_15", :b=>"b_15", :c=>"c_15 ", :d=>"pass"},  "16" => {:a=>"d_16", :b=>"e_16", :c=>"f_16 ", :d=>"fail"}} 

actual output :

{"15"=> {:a=>"d_16", :b=>"e_16", :c=>"f_16 ", :d=>"fail"},  "16"=> {:a=>"d_16", :b=>"e_16", :c=>"f_16 ", :d=>"fail"}} 

please !!!! :(

after first iteration got:

h == {"15" => {:a=>"a_15", :b=>"b_15", :c=>"c_15 ", :d=>"pass"}} 

where value is reference mod. during second iteration change mod, apparently changes value of h['15'], is referencing mod.

to quick fix that:

h[k] = mod.dup 

the above produce cloned version of mod. check described behaviour, might run original code , do:

h.values.each { |v| puts v.__id__ } 

the above print the identifiers of objects , you’ll see keys of resulting array referencing same object.


Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -