37

I want to "flatten" (not in the classical sense of .flatten) down a hash with varying levels of depth, like this:

{
  :foo => "bar",
  :hello => {
    :world => "Hello World",
    :bro => "What's up dude?",
  },
  :a => {
    :b => {
      :c => "d"
    }
  }
}

down into a hash with one single level, and all the nested keys merged into one string, so it would become this:

{
  :foo => "bar",
  :"hello.world" => "Hello World",
  :"hello.bro" => "What's up dude?",
  :"a.b.c" => "d"
}

but I can't think of a good way to do it. It's a bit like the deep_ helper functions that Rails adds to Hashes, but not quite the same. I know recursion would be the way to go here, but I've never written a recursive function in Ruby.

1
  • Will it be useful if you convert your hash in OpenStruct object (the way Rails do it)? Edit: I now realized that it won't perform it recursively in object. But recursive-open-struct seems like a solution.
    – kiddorails
    Commented May 7, 2014 at 14:57

7 Answers 7

62

You could do this:

def flatten_hash(hash)
  hash.each_with_object({}) do |(k, v), h|
    if v.is_a? Hash
      flatten_hash(v).map do |h_k, h_v|
        h["#{k}.#{h_k}".to_sym] = h_v
      end
    else 
      h[k] = v
    end
   end
end

flatten_hash(:foo => "bar",
  :hello => {
    :world => "Hello World",
    :bro => "What's up dude?",
  },
  :a => {
    :b => {
      :c => "d"
    }
  })
# => {:foo=>"bar", 
# =>  :"hello.world"=>"Hello World", 
# =>  :"hello.bro"=>"What's up dude?", 
# =>  :"a.b.c"=>"d"} 
2
  • 1
    Brilliant, this saves me a day of headaches. And it's nice and simple. Commented May 7, 2014 at 21:16
  • Excellent. Probably you want to change the map for an each.
    – jgomo3
    Commented Feb 26, 2020 at 18:35
15

Because I love Enumerable#reduce and hate lines apparently:

def flatten_hash(param, prefix=nil)
  param.each_pair.reduce({}) do |a, (k, v)|
    v.is_a?(Hash) ? a.merge(flatten_hash(v, "#{prefix}#{k}.")) : a.merge("#{prefix}#{k}".to_sym => v)
  end
end

irb(main):118:0> flatten_hash(hash)
=> {:foo=>"bar", :"hello.world"=>"Hello World", :"hello.bro"=>"What's up dude?", :"a.b.c"=>"d"}
1
  • A little piece of code review, to not repeat the a.merge() call twice: a.merge(v.is_a?(Hash) ? flatten_hash(v, "#{prefix}#{k}.") : { "#{prefix}#{k}".to_sym => v }). Also, pretty sure it'd be better to use .merge!. Great answer overall, 5 lines of a well-readable code is always better than this monstrosity with the most votes. Kudos.
    – wscourge
    Commented Jan 15, 2023 at 8:10
8

The top voted answer here will not flatten the object all the way, it does not flatten arrays. I've corrected this below and have offered a comparison:

x = { x: 0, y: { x: 1 }, z: [ { y: 0, x: 2 }, 4 ] }

def top_voter_function ( hash )
  hash.each_with_object( {} ) do |( k, v ), h|
    if v.is_a? Hash
      top_voter_function( v ).map do |h_k, h_v|
        h[ "#{k}.#{h_k}".to_sym ] = h_v
      end
    else
      h[k] = v
    end
  end
end

def better_function ( a_el, a_k = nil )
  result = {}

  a_el = a_el.as_json

  a_el.map do |k, v|
    k = "#{a_k}.#{k}" if a_k.present?
    result.merge!( [Hash, Array].include?( v.class ) ? better_function( v, k ) : ( { k => v } ) )
  end if a_el.is_a?( Hash )

  a_el.uniq.each_with_index do |o, i|
    i = "#{a_k}.#{i}" if a_k.present?
    result.merge!( [Hash, Array].include?( o.class ) ? better_function( o, i ) : ( { i => o } ) )
  end if a_el.is_a?( Array )

  result
end

top_voter_function( x ) #=> {:x=>0, :"y.x"=>1, :z=>[{:y=>0, :x=>2}, 4]}
better_function( x ) #=> {"x"=>0, "y.x"=>1, "z.0.y"=>0, "z.0.x"=>2, "z.1"=>4} 

I appreciate that this question is a little old, I went looking online for a comparison of my code above and this is what I found. It works really well when used with events for an analytics service like Mixpanel.

4
  • As a tip, I recommend using the gem 'humanize' to make the numbers more readable.
    – Oscar
    Commented Nov 23, 2016 at 1:38
  • Thank you. My question was specifically for flattening hashes, though, and I actually didn't want arrays to be flattened for my use case back then. Commented Nov 24, 2016 at 14:24
  • No worries. Actually, there's no mention of arrays in the original question at all
    – Oscar
    Commented Feb 24, 2017 at 1:53
  • 3
    Thanks for submitting, I found this very useful!
    – Dan R
    Commented May 15, 2017 at 14:55
3

Or if you want a monkey-patched version or Uri's answer to go your_hash.flatten_to_root:

class Hash
  def flatten_to_root
    self.each_with_object({}) do |(k, v), h|
      if v.is_a? Hash
        v.flatten_to_root.map do |h_k, h_v|
          h["#{k}.#{h_k}".to_sym] = h_v
        end
      else
        h[k] = v
      end
    end
  end
end
1
2

In my case I was working with the Parameters class so none of the above solutions worked for me. What I did to resolve the problem was to create the following function:

def flatten_params(param, extracted = {})
    param.each do |key, value|
        if value.is_a? ActionController::Parameters
            flatten_params(value, extracted)
        else
            extracted.merge!("#{key}": value)
        end
    end
    extracted
end

Then you can use it like flatten_parameters = flatten_params(params). Hope this helps.

1

Here's a solution that worked for me:

class Hash
  # Test with:
  # {
  #   s: 1,
  #   s2: '2',
  #   n1: {},
  #   n2: { a: 1 },
  #   n3: { a: { b: 1, c: [2, 3], d: { e: 1, f: [4, 5, 'x'] } } },
  #   n4: [],
  #   n5: [1],
  #   n6: [[[[[[[['treasure', [], 1, 'n', {}, { a: 1, b: [2, 3], c: { d: 1, e: [4, 5] } }]]]]]]]],
  #   n7: [{ a: 1, b: [2, 3], c: { d: 1, e: [4, 5] } }, 'y'],
  # }.to_dotted_keys
  def to_dotted_keys(parent_key = nil, flattened_hash = {})
    each do |key, value|
      current_key = parent_key ? "#{parent_key}.#{key}" : key.to_s

      if value.is_a?(Hash) && !value.empty?
        value.to_dotted_keys(current_key, flattened_hash)
      elsif value.is_a?(Array) && !value.empty?
        value.each_with_index do |item, index|
          if item.is_a?(Hash) || item.is_a?(Array)
            { index => item }.to_dotted_keys(current_key, flattened_hash)
          else
            flattened_hash["#{current_key}.#{index}"] = item
          end
        end
      else
        flattened_hash[current_key] = value
      end
    end

    flattened_hash
  end
end

0

Just in case, that you want to keep their parent

def flatten_hash(param)
  param.each_pair.reduce({}) do |a, (k, v)|
    v.is_a?(Hash) ? a.merge({ k.to_sym => '' }, flatten_hash(v)) : a.merge(k.to_sym => v)
  end
end

hash = {:foo=>"bar", :hello=>{:world=>"Hello World", :bro=>"What's up dude?"}, :a=>{:b=>{:c=>"d"}}}

flatten_hash(hash)

# {:foo=>"bar", :hello=>"", :world=>"Hello World", :bro=>"What's up dude?", :a=>"", :b=>"", :c=>"d"}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.