class Object
def dclone
case self
when Fixnum,Bignum,Float,NilClass,
FalseClass,TrueClass
klone = self
when Hash
klone = self.clone
self.each{ k,v klone[k] = v.dclone}
when Array
klone = self.clone
klone.clear
self.each{ v klone << v.dclone}
else
klone = self.clone
end
klone.instance_variables.each { v
klone.instance_variable_set(v,
klone.instance_variable_get(v).dclone)
}
klone
end
end
It would help if you wrap the code in three backticks. See Discourse Guide: Code Formatting - Meta - Stonehearth Discourse.
Also I’m not sure what you’re wanting to do. Is calling my_obj.clone
not enough?
Throughout the Crystal standard library, #clone
is meant to be a deep copy, whereas #dup
is a shallow copy. So if you’re using existing types, you should already be able to use #clone
to do a deep copy. If you’re using your own types, you should write clone methods for each type or write a module with a #clone
method like the one you have and include it in your types rather than re-opening Object
.
https://crystal-lang.org/api/Object.html#def_clone-macro Might be of use here. Can just add def_clone
on your custom type and it handles generating the #clone
method that returns a copy of the object with all instance variables cloned.