Created
June 13, 2019 07:49
-
-
Save LolWalid/4466e8c70243785abd3ee8ff2f947927 to your computer and use it in GitHub Desktop.
Extract Values and Keys from Nested Hash
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
test_hash = { | |
a: 1, | |
b: 2, | |
c: { | |
d: 4, | |
e: 5, | |
a: 1 | |
} | |
} | |
# We want to extract all uniq keys found in "my_hash" | |
# for this recursive method, we need to add an accumulator, "founded_keys" that | |
# will store all keys we found | |
def extract_keys_from_hash(my_hash, founded_keys = []) | |
my_hash.each do |key, value| | |
# Add the founded key in the accumulator | |
founded_keys.push(key) | |
if value.is_a?(Hash) | |
# Our value is a Hash, so there is keys to be found ! | |
# the method call itself to extract the keys in "value" and add them | |
# in founded_keys, our accumulator | |
extract_keys_from_hash(value, founded_keys) | |
end | |
end | |
# we don't want duplicate keys ! | |
founded_keys.uniq | |
end | |
# should display true | |
puts extract_keys_from_hash(test_hash) == [:a, :b, :c, :d, :e] |
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
test_hash = { | |
a: 1, | |
b: 2, | |
c: { | |
d: 4, | |
e: 5, | |
a: 1 | |
} | |
} | |
# We want to extract all values found in "my_hash" | |
# for this recursive method, we need to add an accumulator, "founded_values" tha | |
# will store all values we found | |
def extract_values_from_hash(my_hash, founded_values = []) | |
my_hash.each do |_key, value| | |
if value.is_a?(Hash) | |
# value is a hash ! We dont want to add into founded_values ! | |
# But there is values inside it! | |
# So we call "extract_values_from_hash" with value as argument | |
# to extract values that are inside "value" | |
extract_values_from_hash(value, founded_values) | |
else | |
# it's not a hash ! So we add it into founded_values | |
founded_values.push(value) | |
end | |
end | |
founded_values | |
end | |
# should display true | |
puts extract_values_from_hash(test_hash) == [1, 2, 4, 5, 1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment