Skip to content

Instantly share code, notes, and snippets.

@jasonneylon
Created May 21, 2014 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonneylon/53128362c75d069b1bf5 to your computer and use it in GitHub Desktop.
Save jasonneylon/53128362c75d069b1bf5 to your computer and use it in GitHub Desktop.
Implementation of Clojure get-in for Ruby hashes
class Hash
def get_in(*keys)
key = keys.first
value = self[key]
return value if keys.count == 1
return nil if keys.count > 1 and !value.respond_to? :get_in
return value.get_in(*keys.drop(1)) if key?(key)
end
end
h = {:a => {:b => {:c => 1}}, b: 2, x: {y: "yikes"}}
puts h.get_in(:a, :b, :c)
puts h.get_in(:b, :g, :f)
puts h.get_in(:x, :y, :z)
puts h.get_in(:x, :y)
puts h.get_in(:x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment