Sha256: 2442ca3ed8dad0f35f21a3e4e282a87ca1ea442e0be2d8ba2bcdba32a3d08058

Contents?: true

Size: 1.42 KB

Versions: 49

Compression:

Stored size: 1.42 KB

Contents

module ActiveTools
  module CoreExtension
    
    module DeepCopy
      # Return the 'deep' brand new copy of Hash, Array or Set. All nested hashes/arrays/sets rebuilded at the same way.
      
      module HashExtension
        def deep_copy(&block)
          self.class.new.tap do |new_hash|
            each do |k, v|
              new_hash[k] = case v
              when Hash, Array, Set then v.deep_copy(&block)
              else
                block_given? ? yield(v) : v.dup rescue v
              end
            end
          end
        end
      end

      module ArrayExtension
        def deep_copy(&block)
          self.class.new.tap do |new_array|
            each do |v|
              new_array << case v
              when Hash, Array, Set then v.deep_copy(&block)
              else
                block_given? ? yield(v) : v.dup rescue v
              end
            end
          end
        end
      end

      module SetExtension
        def deep_copy(&block)
          self.class.new.tap do |new_set|
            each do |v|
              new_set << case v
              when Hash, Array, Set then v.deep_copy(&block)
              else
                block_given? ? yield(v) : v.dup rescue v
              end
            end
          end
        end
      end
      
      ::Hash.send(:include, HashExtension)
      ::Array.send(:include, ArrayExtension)
      ::Set.send(:include, SetExtension)
      
    end
  end
end

Version data entries

49 entries across 49 versions & 1 rubygems

Version Path
active_tools-0.2.5 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.2.4 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.2.3 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.2.2 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.2.1 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.2.0 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.1.4 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.1.3 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.1.2 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.1.1 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.1.0 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.0.52 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.0.51 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.0.50 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.0.42 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.0.41 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.0.40 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.0.39 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.0.38 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.0.37 lib/active_tools/core_extension/deep_copy.rb