Created
March 1, 2018 12:46
-
-
Save jsugarman/11e309204738be7a411f79e77a03425c to your computer and use it in GitHub Desktop.
Hash extensions
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
| module HashExtension | |
| def all_keys | |
| each_with_object([]) do |(k, v), keys| | |
| keys << k | |
| keys.concat(v.select { |el| el.is_a?(Hash) }.flat_map(&:all_keys)) if v.is_a? Array | |
| keys.concat(v.all_keys) if v.is_a? Hash | |
| end | |
| end | |
| def all_values_for(key) | |
| each_with_object([]) do |(k, v), values| | |
| values << v if k.eql?(key) | |
| values.concat(v.select { |el| el.is_a?(Hash) }.flat_map { |el| el.all_values_for(key) }) if v.is_a? Array | |
| values.concat(v.all_values_for(key)) if v.is_a? Hash | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To use just add below to an initializer or whenever needed: