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

从Nosql数据的散列中获取数据的通用ruby方法实现,ruby,Ruby,如何使用自定义ruby实现从散列的散列中获取特定值 我有一个nosql数据,它以这种特殊的格式出现: {:bookname=>"The Fight for Guadalcanal", :sourceSystemId=>"d4ba4799-atil45-4a", :checkouttimestamp=>"2018-12-12T04:38:34.476796700Z",:firedevents=>[{:operation=>"GET", :entity=>"w

如何使用自定义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))
这确实给我带来了价值

但问题是,数据集中的数组或散列的数量可能随每次操作的不同而不同,因此我正在寻找一种方法,该方法在将键作为参数传递时为我提供一个值


e、 g.:
ruby\u mthod(sourceSystemId.to\u sym)
应该会让我
d4ba4799-atil45-4a
获取足够的
sourceSystemId
(假设您的数据在
h
):

如果你想找一些更通用的东西,看看。它允许您以整洁的方式链接哈希访问:

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

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

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

您可以递归地遍历哈希,如下所示:

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

h.dig(:firedevents,0,:keys,0,:value,:FieldString)
中的“一个在将键作为参数传递时给我一个值的方法”——这正是它的作用:从给定键的哈希返回一个值。好像你还想要别的东西。请澄清你的问题。
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