zoukankan      html  css  js  c++  java
  • HASH的dig方法判断key是否存在及是否有值

    dig(key, ...) → objectclick to toggle source

    Extracts the nested value specified by the sequence of idx objects by calling dig at each step, returning nil if any intermediate step is nil.

    http://ruby-doc.org/core-2.4.0/Hash.html#method-i-dig

    h = { foo: {bar: {baz: 1}}}
    
    h.dig(:foo, :bar, :baz)           #=> 1
    h.dig(:foo, :zot, :xyz)           #=> nil
    
    g = { foo: [10, 11, 12] }
    g.dig(:foo, 1)                    #=> 11
    g.dig(:foo, 1, 0)                 #=> TypeError: Integer does not have #dig method
    g.dig(:foo, :bar)                 #=> TypeError: no implicit conversion of Symbol into Integer

    举例子:

                if item["ui_type"]["pos"].present?
                  display_item.x_axis = item["ui_type"]["pos"]["x"] if item["ui_type"]["pos"]["x"].present?
                  display_item.y_axis = item["ui_type"]["pos"]["y"] if item["ui_type"]["pos"]["y"].present?
                  display_item.width = item["ui_type"]["pos"]["w"]  if item["ui_type"]["pos"]["w"].present?
                  display_item.height = item["ui_type"]["pos"]["h"] if item["ui_type"]["pos"]["h"].present?
                end

    改为

                display_item.x_axis = item["ui_type"]["pos"]["x"] if item.dig("ui_type", "pos", "x").present?
                display_item.y_axis = item["ui_type"]["pos"]["y"] if item.dig("ui_type", "pos", "y").present?
                display_item.width = item["ui_type"]["pos"]["w"]  if item.dig("ui_type", "pos", "w").present?
                display_item.height = item["ui_type"]["pos"]["h"] if item.dig("ui_type", "pos", "h").present?
  • 相关阅读:
    Range
    cache
    从头到尾彻底解析Hash 表算法
    教你如何迅速秒杀掉:99%的海量数据处理面试题
    秒杀抢购思路以及高并发下数据安全
    Nginx+Tomcat负载均衡
    强大的Spring缓存技术(上)
    强大的Spring缓存技术(中)
    强大的Spring缓存技术(下)
    (转)C#中的 break 与continue 的使用和注意
  • 原文地址:https://www.cnblogs.com/iwangzheng/p/6339733.html
Copyright © 2011-2022 走看看