Last active
August 29, 2015 14:16
-
-
Save meaganewaller/4c2b972d4f44205b209a to your computer and use it in GitHub Desktop.
Hash Challenge
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
hash = { | |
a: 1, | |
b: 2, | |
c: { | |
d: 3, | |
e: { | |
f: 4 | |
}, | |
g: 5 | |
} | |
} | |
# some function like flatten_hash(hash) should return [:a, :b, :c, :d, :e, :f, :g] |
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
def flatten_hash(hash) | |
arr = [] | |
hash.each do |k, v| | |
arr << k | |
end | |
arr | |
end |
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
def flatten_hash(hash) | |
arr = [] | |
hash.each do |k, v| | |
if v.is_a?(Hash) | |
v.each do |k2, v2| | |
arr << k2 | |
end | |
end | |
arr << k | |
end | |
arr | |
end |
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
def flatten_hash(hash) | |
arr = [] | |
hash.each do |k, v| | |
if v.is_a?(Hash) | |
v.each do |k2, v2| | |
if v2.is_a?(Hash) | |
v2.each do |k3, v3| | |
arr << k3 | |
end | |
end | |
arr << k2 | |
end | |
end | |
arr << k | |
end | |
arr | |
end |
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
def flatten_hash(hash, arr=[]) | |
hash.each do |k, v| | |
if v.is_a?(Hash) | |
flatten_hash(v, arr) | |
end | |
arr << k | |
end | |
arr | |
end |
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
describe "FlattenHash" do | |
it "returns an array of keys for a nested hash" do | |
expected = [:a, :b, :c, :d, :e, :f, :g] | |
actual = flatten_hash(hash) | |
expect(actual).to match_array(expected) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment