Last active
August 29, 2015 14:12
-
-
Save Kameshwaran/a24b0294b632608f0a1a to your computer and use it in GitHub Desktop.
Simple search on Hash
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 search(hash, keyword) | |
if (hash.respond_to?(:keys) && hash.keys.include?(keyword)) | |
hash[keyword] | |
elsif hash.respond_to?(:find) | |
result = nil | |
hash.values.find { |value| result = search(value, keyword) } | |
result | |
end | |
end | |
# hash = { | |
# "a" => "b", | |
# "c" => "d", | |
# "e" => { | |
# "f" => "g", | |
# "h" => { | |
# "i" => "j", | |
# "k" => "l" | |
# } | |
# } | |
# } | |
# puts search(hash, "a") => "b" | |
# puts search(hash, "i") => "j" | |
# puts search(hash, "n") => nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment