Imagine I have an array like this
array = [4,"hello",[[3],:d,7,[:a,"seven"]]]
class Array
def deep_collect_by_elem_type_as_hash()
e = {}
self.each(){|x|
if x.is_a?(Array)
e.merge(x.deep_collect_by_elem_type_as_hash)
end
if !x.is_a?(Array)
if e.has_key?(x.class)
e[x.class]<<x
else
e[x.class] = [x]
end
end
}
return e
end
I want all my arrays to create an hash in which there are keys containing the different classes that are in my Array. Their values will be the actual elements for each class.
So it would look like this:
{Fixnum=>[4, 3, 7], String=>["hello", "seven"], Symbol=>[:d, :a]}
I want to solve the whole thing without using flatten, but doing it recrusive. Te flatten solution could look like this:
def deep_collect_by_elem_type_as_hash1()
e = {}
flat= self.flatten()
flat.each(){|x|
if e.has_key?(x.class)
e[x.class]<<x
else
e[x.class] = [x]
end
}
return e
end
For those wondering why I do not want to use flatten: I still have problems fully understanding how to implement recursive methods, and therefore this is a question to give me a better understanding.
I think I somehow have to implement merge with a block, but I cannot figure out a proper block. merge(x.deep_collect_by_elem_type_as_hash(){|k,v1,v2| help}