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?

 

posted @ 2017-01-22 11:06  冰凌花花~  阅读(737)  评论(0编辑  收藏  举报