Ruby: 2.5.1  -  Hash#dig

前提:一个已知的Hash数据,然后知道一组键值. 从而想获取最终的value.

在我们数据中有一个名为data jsonb 字段, 然后不同Source的数据,数据是结构是不一样的。如以下示例:

1. { "values" => 10 } 
2. { "followers"=> { "count"=>0 } }
3. { "financials"=>[{"margin"=>{"value"=>10}}] }
4. { "social" => { "linkedin" => { "employees" => {"value" => 234} } } }

本来想着拓展一下Hash类,最后发现Ruby中已经实现了 Hash#dig

class Hash
  # Getting ruby hash values by an array of keys
  #   Already a good method in Ruby.  .dig
  #
  def deep_find(*args)
    value = self

    args.each do |k|
      value = value[k]
    end

    value
  end
end

接下来,我们看看如何使用Hash#dig:

a = { "values" => 10 } 
a.dig('values') => 10

a = { "followers"=> { "count"=>0 } }
keys = ['followers', 'count']
a.dig(*keys) => 0

a = { "financials"=>[{"margin"=>{"value"=>10}}] }
keys = ['financials', 0, 'margin', 'value']
a.dig(*keys) => 10

a = { "social" => { "linkedin" => { "employees" => {"value" => 234} } } }
keys = ['social', 'linkedin', 'employees', 'value']
a.dig(*keys) => 234