Skip to content

Instantly share code, notes, and snippets.

@ifesdjeen
Created August 14, 2012 09:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ifesdjeen/3347760 to your computer and use it in GitHub Desktop.
Save ifesdjeen/3347760 to your computer and use it in GitHub Desktop.
Clojure get_in in ruby
# 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