I am trying to figure out a way to clean up a hash result in ruby. What I mean by clean is that I have a hash that contains hashes that are empty at different nested levels. Programmatically, how would I do this in ruby? I'm new to ruby here and this is what I have so far, and I'm stuck. Thank you in advance.
@main_hash.each |key, value| do
if(value.class == Hash && !value.empty?) do
# loop in further to delete
elsif(value.class == Hash && value.empty?)
# delete this value
end
end
UPDATE: I think I'll have to go with a recursive method to do this. But my trouble is, how can I delete the actual value hash from the correct level of the main hash when the empty value hash is found.
def compactify_hash(main_hash)
main_hash.each |key, value| do
if(value.class == Hash && !value.empty?) do
compactify_hash(value)
elsif(value.class == Hash && value.empty?)
# how to delete this hash?
end
end
end
Aucun commentaire:
Enregistrer un commentaire