-
-
Save TRex22/5f3d75aef2727d9c536f017245b0afd1 to your computer and use it in GitHub Desktop.
Delete all empty/false elements from Array of key value pairs recursively
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 ArrayKeyValueCleaner | |
extend self | |
# This makes use of a recursive proc to recurse into a deeply | |
# nested set of arrays | |
# | |
# At the deepest array it will check if the next set of children | |
# are not arrays and make sure they are valid key value pairs | |
def call(value) | |
return value unless value.is_a?(Array) | |
p = proc do |*args| | |
v = args.last | |
v.delete_if(&p) if v.respond_to?(:delete_if) | |
v.nil? || v.blank? || has_no_key_value_pair(v) | |
end | |
value.delete_if(&p) | |
end | |
def has_no_key_value_pair(array) | |
array.is_a?(Array) && | |
!array.first.is_a?(Array) && | |
array.length != 2 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I had a very specific need for key value pairs