Skip to content

Instantly share code, notes, and snippets.

@TRex22
Forked from longlostnick/gist:1251339
Last active October 22, 2018 15:20
Show Gist options
  • Save TRex22/5f3d75aef2727d9c536f017245b0afd1 to your computer and use it in GitHub Desktop.
Save TRex22/5f3d75aef2727d9c536f017245b0afd1 to your computer and use it in GitHub Desktop.
Delete all empty/false elements from Array of key value pairs recursively
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
@TRex22
Copy link
Author

TRex22 commented Oct 22, 2018

I had a very specific need for key value pairs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment