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.0.15 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.0.14 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.0.13 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.0.12 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.0.11 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.0.10 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.0.6 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.0.5 lib/active_tools/core_extension/deep_copy.rb
active_tools-0.0.3 lib/active_tools/core_extension/deep_copy.rb