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?
  • 相关阅读:
    scala
    数据结构(01)
    基本算法(07)
    基本算法(06)
    基本算法(05)
    git pull文件时和本地文件冲突的问题
    获取两个日期之间的日期形成一个集合
    lombok的简单介绍(2)
    springboot启动报错
    逆向工程的创建
  • 原文地址:https://www.cnblogs.com/iwangzheng/p/6339733.html
Copyright © 2011-2022 走看看