Skip to content

Instantly share code, notes, and snippets.

@GiaoGiaoCat
Last active June 12, 2016 06:32
Show Gist options
  • Save GiaoGiaoCat/9fa19509058cf09c9e76 to your computer and use it in GitHub Desktop.
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.
# 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
@GiaoGiaoCat
Copy link
Author

module CoreExtensions
  module GetIN
    def get_in(enum, default = nil)
      leap = Proc.new do |mem, var, default|
        case var
        when Fixnum then mem = mem.at(var)
        when Symbol, String then mem = mem.fetch(var, default)
        end
      end

      enum.inject(self) { |mem, var| leap.call(mem, var, default) }
    rescue NoMethodError
      puts '参数错误'
    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]
p y.get_in "a"

# >> 3
# >> nil
# >> "Sally Clojurian"
# >> "Yeah"
# >> :hamster
# >> 参数错误

@GiaoGiaoCat
Copy link
Author

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