Flatten a Hash!

Flattening an array is a standard question in interviews, especially for modern languages like python and ruby. I just thought trying to flatten a hash would be much more interesting.

Here is my attempt at converting something like

{“a”=>1, “b”=>{“c”=>3}, “b2″=>{“c2″=>{“d2″=>2, “d3″=>8, “b2″=>9}}}

into

{“a”=>1, [“b2”, “c2”]=>9, [“b2”, “c2”, “d2”]=>2, [“b2”, “c2”, “d3”]=>8, [“b”, “c”]=>3}

require 'enumerator'
class Hash
 def flat_each(prefix=[], &block)
      each do |key, value|
           if value.is_a?(Hash)
                 value.flat_each(prefix + [key], &block)
           else
                 yield prefix + [key], value
           end
     end
end

main_hash = Hash.new
given = {"a"  => 1,"b"  => { "c" => 3 },"b2" => {"c2" => {"d2" => 2,"d3"  => 8,"b2"  => 9}}}
given.to_enum(:flat_each).collect { |k,v| main_hash.merge!({ (k.size == 1) ?  k.first : k.uniq  => v}) }
puts main_hash

Algorithm adapted from Ruby Forum.
Not sure this is what you would call flattening a hash, but this is the best I could rustle up in half an hour.

Categories:

Tags: ///

About “Mujtaba Hussain”

I have no idea what to write here :(