用于从Nosql数据的散列中获取数据的通用ruby方法实现

问题描述 投票:0回答:2

如何使用自定义ruby实现从哈希哈希中获取特定值

我有一个以这种特殊格式出现的nosql数据:

{:bookname=>"The Fight for Guadalcanal", 
:sourceSystemId=>"d4ba4799-atil45-4a", 
:checkouttimestamp=>"2018-12-12T04:38:34.476796700Z",:firedevents=>[{:operation=>"GET", :entity=>"warbooks", :keys=>[{:name=>"book_guid", :value=>{:FieldString=>"e33almmatter-syslibrary"}}], 
 :attributes=>[{:libLocation=>"a44364", :value=>{:FieldInteger=>3994}}, {:name=>"big_response", :value=>{:FieldString=>"The Battle for Enderson Field, also"}}],
 :customizable=>true}]}

在ruby中是否有方法提供密钥作为参数参数?

我知道ruby中有fetch方法可以获得值:

test.fetch(:firedevents,()).fetch(:operation))

这确实让我获得了GET的价值

但问题是我有数据集中的数组或散列数可能会因每个操作而异,所以我在寻找一个方法,它给我一个关于传递键作为参数的值。

例如:ruby_mthod(sourceSystemId.to_sym)应该让我d4ba4799-atil45-4a

ruby
2个回答
1
投票

获取将足以获得sourceSystemId(假设您的数据位于h):

> h.fetch(:sourceSystemId)
# => "d4ba4799-atil45-4a"

如果您正在寻找更通用的东西,请查看Hash#dig。它允许您以一种巧妙的方式链接哈希访问:

> h.fetch(:firedevents).first.fetch(:keys).first.dig(:value, :FieldString)
# => "e33almmatter-syslibrary"

编辑:

正如@Stefan建议的那样,#dig可以用于整个操作:

> h.dig(:firedevents, 0, :keys, 0, :value, :FieldString)
# => "e33almmatter-syslibrary"

0
投票

您可以递归遍历哈希:

def deep_find(key, object=self, found=nil)
    if object.respond_to?(:key?) && object.key?(key)
      return object[key]
    elsif object.is_a? Enumerable
      object.find { |*a| found = deep_find(key, a.last) }
      return found
    end
  end

或者你可以使用来自hashie gem的deep_find

© www.soinside.com 2019 - 2024. All rights reserved.