[英]Search within a Hash containing hashes
我在Ruby中有以下哈希值:
{
0 => {
:method=>\"POST \",
:path=>\"/api/online/platforms/fb/users/191023/add_infos\",
:host=>\"host.12\",
:duration=>\"1221\"
},
1 => {
:method=>\"GET \",
:path=>\"/api/customer/191023/messages\",
:host=>\"host.8\",
:duration=>\"99\"
},
2 => {
:method=>\"POST \",
:path=>\"/logs/data\",
:host=>\"host.10\",
:duration=>\"142\"
},
3 => {
:method=>\"POST \",
:path=>\"/api/customer/191023\",
:host=>\"host.6\",
:duration=>\"243\"
}
4 => {
:method=>\"POST \",
:path=>\"/api/customer/191023\",
:host=>\"host.2\",
:duration=>\"132\"
}
}
我想在這些哈希中進行簡單的搜索,以找到將其方法密鑰設置為POST
並將路徑密鑰設置為"/api/customer/191023"
。 等效於data.where(method: "POST", path: "/api/customer/191023")
。
首先,我嘗試了一個僅基於method
的select
:
hs = hash.select{|k, h| h[:method] == "POST" }
但是返回的哈希為空。
謝謝。
M.
我在:method
鍵的值之后看到了空格,因此請嘗試regexp進行匹配,如下所示:
hs = hash.select {|k, h| h[:method] =~ /POST/ && h[:path] == '/api/customer/191023' }
要查找頻率最高的主機值,請執行以下操作:
hs = hash.values.group_by { |h| h[:host] =~ /host\.(\d+)/ && $1.to_i || 0 }.to_a
hs.reduce([-1,0]) { |sum,v| v[1].size > sum[1] && [ v[0], v[1].size ] || sum }.first
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.