Skip to content

Instantly share code, notes, and snippets.

@RobertWSaunders
Created March 4, 2020 04:24
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 RobertWSaunders/368661a7ecc00f9e28f0910f9dedf9aa to your computer and use it in GitHub Desktop.
Save RobertWSaunders/368661a7ecc00f9e28f0910f9dedf9aa to your computer and use it in GitHub Desktop.
# these two methods appear to be the same but
# because one accepts memo as an argument
# it hackily gets away with the actual
# problem which is that `+` doesn't mutate memo
# since Ruby passes args by reference it
# works, ngl this took me sometime to find
# why one worked and the other didn't
# works
def keys_for_deep_find(hash, memo: [], &block)
hash.each do |k, v|
if v.is_a?(Hash)
memo + keys_for_deep_find(v, memo: memo, &block)
else
if block.call(k, v)
memo.push(k)
end
end
end
memo
end
# does not work
def keys_for_deep_find(hash, &block)
hash.each_with_object([]) do |(k, v), memo|
if v.is_a?(Hash)
memo + keys_for_deep_find(v, &block)
else
if block.call(k, v)
memo.push(k)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment