Created
August 14, 2012 09:21
-
-
Save ifesdjeen/3347760 to your computer and use it in GitHub Desktop.
Clojure get_in in ruby
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
# Returns value from hash based on the path | |
# | |
# @param hash [Hash] - hash to retrieve values from | |
# @param path [Array] - non-empty array representing recursive path | |
# | |
# @returns [Object] - an object located within an array on the given path | |
# | |
# Examples: | |
# | |
# get_in({:a => {:b => {:c => 2}}}, [:a, :b, :c]) # => 2 | |
# get_in({:a => {:b => {:c => 2}}}, [:a, :e, :c]) # => nil | |
# get_in({:a => {:b => {:c => 2}}}, [:a, :b]) # => {:c=>2} | |
# | |
def get_in(hash, path) | |
raise "Path should be an array!" unless path.is_a?(Array) | |
raise "Path should not be empty!" if path.empty? | |
res = hash.fetch(path.shift, nil) | |
if path.empty? || res.nil? | |
res | |
else | |
get_in(res, path) | |
end | |
end # get_in(hash) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment