Skip to content

Instantly share code, notes, and snippets.

@GBH
Created February 25, 2014 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GBH/9218575 to your computer and use it in GitHub Desktop.
Save GBH/9218575 to your computer and use it in GitHub Desktop.
Hash#deep_slice
class Hash
def deep_slice(*allowed_keys)
sliced = { }
allowed_keys.each do |allowed_key|
if allowed_key.is_a?(Hash)
key = allowed_key.keys.first
sliced[key] = self[key].deep_slice(*[allowed_key.values].flatten) if self[key]
else
sliced[allowed_key] = self[allowed_key] if self[allowed_key]
end
end
sliced
end
end
class DeepSliceTest < Minitest::Test
def test_deep_slice
hash = {:a => 1, :b => {:c => 2, :d => {:e => 3, :f => 4}}, :g => 5}
assert_equal hash, hash.deep_slice(:a, :b, :g)
assert_equal ({:a => 1}), hash.deep_slice(:a)
assert_equal ({:b => {:c => 2}}), hash.deep_slice(:b => :c)
assert_equal ({
:b => {:c => 2, :d => {:e => 3, :f => 4}},
}), hash.deep_slice(:b => [:c, :d])
assert_equal ({
:b => {:c => 2, :d => {:e => 3}},
}), hash.deep_slice(:b => [:c, :d => :e])
assert_equal ({
:b => {:d => {:e => 3}},
}), hash.deep_slice(:b => {:d => :e})
assert_equal ({}), hash.deep_slice(:x, :y, :z)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment