Created
April 22, 2023 04:25
-
-
Save nsmmrs/f97689c1f7240f21f82f1d359b546365 to your computer and use it in GitHub Desktop.
Hash#deep_slice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Hash | |
def deep_slice(schema) | |
self.class.deep_slice(self, schema) | |
end | |
def self.deep_slice(hash, schema) | |
nested_schemas = schema.last.is_a?(Hash) ? schema.last : {} | |
keys = schema.reject{|e| e.is_a?(Hash) } + nested_schemas.keys | |
hash.slice(*keys).map do |k,v| | |
schema = nested_schemas[k] | |
v = case | |
when schema.nil? | |
v | |
when v.is_a?(Hash) | |
deep_slice(v, schema) | |
when v.is_a?(Array) | |
v.map{|e| deep_slice(e, schema.first) } | |
when v.nil? | |
if schema.count == 1 && schema.first.is_a?(Array) | |
[] | |
else | |
{} | |
end | |
end | |
[k,v] | |
end.to_h | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment