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?
  • 相关阅读:
    vue 组件复用不刷新
    ES6删除对象中的某个元素
    UI组件--element-ui--Table组件自定义合计行
    UI组件--element-ui合计行在横向滚动条下面的解决方法
    java笔记 -- 数组
    java笔记 -- 输入输出
    java笔记 -- java字符串
    java笔记 -- 数学函数与常量
    java笔记 -- java运算
    java笔记 -- java变量与常量的声明
  • 原文地址:https://www.cnblogs.com/iwangzheng/p/6339733.html
Copyright © 2011-2022 走看看