Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Collapse a multi-dimensional hash into a single-dimensional hash (See related posts)

#!/usr/bin/env ruby

require 'test/unit'

class Hash
  def flatten_keys(newhash={}, keys=nil)
    self.each do |k, v|
      k = k.to_s
      keys2 = keys ? keys+"."+k : k
      if v.is_a?(Hash)
        v.flatten_keys(newhash, keys2)
      else
        newhash[keys2] = v
      end
    end
    newhash
  end
end

class FlattenKeysTest < Test::Unit::TestCase
  def test_with_string_keys
    test_hash = {
      'bar' => {
        'baz' => {
          'quux' => 1,
          'blargh' => 2,
          'zap' => 3,
          'zoo' => 4
        }
      },
      'zing' => 5
    }
    expected_hash = {
      'bar.baz.quux' => 1,
      'bar.baz.blargh' => 2,
      'bar.baz.zap' => 3,
      'bar.baz.zoo' => 4,
      'zing' => 5
    }
    assert_equal expected_hash, test_hash.flatten_keys
  end
  
  def test_with_symbol_keys
    test_hash = {
      :bar => {
        :baz => {
          :quux => 1,
          :blargh => 2,
          :zap => 3,
          :zoo => 4
        }
      },
      :zing => 5
    }
    expected_hash = {
      'bar.baz.quux' => 1,
      'bar.baz.blargh' => 2,
      'bar.baz.zap' => 3,
      'bar.baz.zoo' => 4,
      'zing' => 5
    }
    assert_equal expected_hash, test_hash.flatten_keys
  end
end

You need to create an account or log in to post comments to this site.


Click here to browse all 7297 code snippets

Related Posts