Last active
June 12, 2016 06:32
-
-
Save GiaoGiaoCat/9fa19509058cf09c9e76 to your computer and use it in GitHub Desktop.
Returns the value in a nested associative structure, where ks is a sequence of keys. Returns nil if the key is not present, or the not-found value if supplied.
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
# https://www.conj.io/store/v1/org.clojure/clojure/1.8.0/clj/clojure.core/get-in | |
module CoreExtensions | |
module GetIN | |
def get_in(enum, default = nil) | |
enum.inject(self) do |mem, var| | |
case var | |
when Fixnum then mem = mem.at(var) | |
when Symbol, String then mem = mem.fetch(var, default) | |
end | |
mem | |
end | |
end | |
end | |
end | |
Array.include CoreExtensions::GetIN | |
Hash.include CoreExtensions::GetIN | |
v = [[1,2,3], [4,5,6], [7,8,9]] | |
x = {username: "sally", profile: {name: "Sally Clojurian", address: {city: "Austin", state: "TX"}}} | |
y = {username: "jimmy", pets: [{name: "Rex", type: :dog}, {name: "Sniffles", type: :hamster}]} | |
p v.get_in [0, 2] | |
p v.get_in [0, 4] | |
p x.get_in [:profile, :name] | |
p x.get_in [:profile, :profile], "Yeah" | |
p y.get_in [:pets, 1, :type] | |
# >> 3 | |
# >> nil | |
# >> "Sally Clojurian" | |
# >> "Yeah" | |
# >> :hamster |
Author
GiaoGiaoCat
commented
Mar 15, 2016
take a look at Hash's dig
method. 😆
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment