Skip to content

Instantly share code, notes, and snippets.

@RhysStansfield
Created January 21, 2016 16:08
Show Gist options
  • Save RhysStansfield/3337b61c974bef2fbcc5 to your computer and use it in GitHub Desktop.
Save RhysStansfield/3337b61c974bef2fbcc5 to your computer and use it in GitHub Desktop.
Recursive Hash
# lib file contents
Hash.class_eval do
# how the hell do we get this to work with []
def recursive_find(key)
return self[key] if has_key?(key)
self
.values
.select { |value| value.is_a?(Hash) }
.find { |hash| hash.has_key?(key) ? hash[key] : hash.recursive_find(key) }
end
end
# spec file contents
require 'spec_helper'
require './lib/recursive_hash'
describe "recursive hash" do
let(:hash) do
{
a: 1,
b: { c: 2 },
d: { e: { f: 3, i: 5 }},
g: { f: 4 }
}
end
it "acts like a normal hash when key present in top level" do
expect(hash.recursive_find(:a)).to be 1
end
it "can retrieve a value from a nested hash if key not present in top level" do
expect(hash.recursive_find(:c)).to be 2
end
it "can retrieve a value from a deeply nested hash if key not in any higher leaf node" do
expect(hash.recursive_find(:i)).to be 5
end
it "can retrieve a value with a duplicated key, which would be the least nested value" do
expect(hash.recursive_find(:f)).to be 4
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment