Hi, welcome to Word of Mike, my little corner of the internet. I am a Software/Web Developer working in North Yorkshire. I mainly write about programming but my other passion is politics so beware. (click to hide)

2015-01-13 00:57:33 UTC

Nested Key Representation from Ruby Hash


I needed a way to compare hash structures, but wasn't bothered about the values, so I wrote this little hash refinement which returns an array of hash key representations in "dot concatenated format", which I can easily diff.

module NestedKeysExtension
  refine Hash do
    def get_nested_keys(prefix = "")
      hash_keys = keys.map { |k| prefix + k.to_s }
      each do |k,v|
        hash_keys += v.get_nested_keys("%s%s." % [prefix, k.to_s]) if v.is_a? Hash
      end
      hash_keys
    end
  end
end

class TestClass
  using NestedKeysExtension

  def initialize(h)
    puts h.get_nested_keys.inspect
  end
end

TestClass.new({a:{x:2, y:3, z:4}, b:{x:3, z:45}})
=> ["a", "b", "a.x", "a.y", "a.z", "b.x", "b.z"]