Skip to content

Instantly share code, notes, and snippets.

@Kameshwaran
Last active August 29, 2015 14:12
Show Gist options
  • Save Kameshwaran/a24b0294b632608f0a1a to your computer and use it in GitHub Desktop.
Save Kameshwaran/a24b0294b632608f0a1a to your computer and use it in GitHub Desktop.
Simple search on Hash
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