0

>Deep cloning for Ruby

>A problem with Ruby is that it does not provide deep cloning. What’s more, some classes produce errors when you issue a clone on them, such as Fixnum.

Here is how you can write a simple deep cloning method that will work for hashes and arrays:


def clone_helper(el)
el_clone = nil
if el.kind_of?(Array)
el_clone = array_clone_helper(el)
elsif el.kind_of?(Hash)
el_clone = hash_clone_helper(el)
else
begin
el_clone = el.clone
rescue TypeError
el_clone = el
end
end
return el_clone
end

def array_clone_helper(arr)
arr.map { |el| clone_helper(el) }
end

def hash_clone_helper(h)
h.inject({}) { |h_clone, kv| h[kv[0]] = clone_helper(kv[1]) }
end

Happy coding..

Leave a Reply

Your email address will not be published. Required fields are marked *