Created
March 4, 2020 04:24
-
-
Save RobertWSaunders/368661a7ecc00f9e28f0910f9dedf9aa to your computer and use it in GitHub Desktop.
This file contains 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
# 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