method
    
    deep_dup
 
  
      v5.0.0.1 - 
      Show latest stable
 - 
    3 notes - 
    Class: Hash
    
  
  
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0
- 3.0.9
- 3.1.0 (0)
- 3.2.1 (0)
- 3.2.8 (38)
- 3.2.13 (0)
- 4.0.2 (-2)
- 4.1.8 (1)
- 4.2.1 (0)
- 4.2.7 (0)
- 4.2.9 (0)
- 5.0.0.1 (0)
- 5.1.7 (0)
- 5.2.3 (0)
- 6.0.0 (0)
- 6.1.3.1 (0)
- 6.1.7.7 (0)
- 7.0.0 (0)
- 7.1.3.2 (0)
- 7.1.3.4 (0)
- What's this?
deep_dup()
  public
  Returns a deep copy of hash.
hash = { a: { b: 'b' } } dup = hash.deep_dup dup[:a][:c] = 'c' hash[:a][:c] # => nil dup[:a][:c] # => "c"
  
    
      Register or 
      log in
      to add new notes.
  
  
  
  
      
     danielglh -  
    August 25, 2014 - (v3.1.0 - v3.2.13)
 danielglh -  
    August 25, 2014 - (v3.1.0 - v3.2.13)
    
  
  
  
       
  
  
  
  
      
     astgtciv -  
    February  2, 2015
 astgtciv -  
    February  2, 2015 
    
  
  
  
       
  
  
  
  
      
     joels -  
    January  6, 2016
 joels -  
    January  6, 2016 
    
  
  
  
       
  
  
  
           danielglh -  
    August 25, 2014 - (v3.1.0 - v3.2.13)
 danielglh -  
    August 25, 2014 - (v3.1.0 - v3.2.13)
    
  
    
    1 thank
     
  
  
  This method does not correctly dup arrays
Watch out because this method does not correctly dup arrays values.
The bug can be reproduced with the following code:
hash = { 'a' => [1,2,3,4] } dup = hash.deep_dup dup['a'].object_id == hash['a'].object_id # should return true
Rails 4 version does not have this issue because it is completely different implementation.
 astgtciv -  
    February  2, 2015
 astgtciv -  
    February  2, 2015 
    
  
    
    0 thanks
     
  
  
  Be careful with cycles
This simplistic implementation (unlike Marshal.load(Marshal.dump(object)) doesn’t handle cycles in objects.
a = {} b = {a: a} a[:b] = b a.deep_dup # SystemStackError: stack level too deep
 joels -  
    January  6, 2016
 joels -  
    January  6, 2016 
    
  
    
    0 thanks
     
  
  
  What about Marshal remote code execution risks?
Good suggestion about using Marshal to avoid cycles, astgtciv, but what about the security risks of doing that?
See http://ruby-doc.org/core-2.2.2/Marshal.html where it states:
By design, ::load can deserialize almost any class loaded into the Ruby process. In many cases this can lead to remote code execution if the Marshal data is loaded from an untrusted source. As a result, ::load is not suitable as a general purpose serialization format and you should never unmarshal user supplied input or other untrusted data. If you need to deserialize untrusted data, use JSON or another serialization format that is only able to load simple, ‘primitive’ types such as String, Array, Hash, etc. Never allow user input to specify arbitrary types to deserialize into.

 RSpec
RSpec Ruby on Rails
Ruby on Rails Ruby
Ruby 
   
   
   
    
     
   = protected
 = protected
   
    