Flattening Array Containing Hashes in Ruby

We ran into an issue in one of our tests in which we needed to take data that was returned in the format of an array of hashes (which could contain nested arrays of hashes), and convert it into a flat hash (no nesting). Here’s a example for us visual people:

[
  { title: 'title' },
  { name: 'name' },
  details: [
    { item1: '1' },
    { item2: '2' }
  ]
]

This needed to be converted to this:

{
  title: 'title',
  name: 'name',
  item1: '1',
  item2: '2'
}

We didn’t have to worry about overlapping keys because we knew beforehand that there would never be duplicate keys in our original data. Here’s the solution I came up with.

def array_to_hash(array)
  array.inject({}) do |memo, hash|
    hash.each do |k,v|
      if v.is_a?(Array)
        memo.merge!(array_to_hash(v))
      else
        memo[k] = v
      end
    end

    memo
  end
end

This handles any level of nesting that you may have. I personally thought it was a simple solution :-).

Advertisements