在包含哈希的哈希中搜索 [英] Search within a Hash containing hashes

查看:106
本文介绍了在包含哈希的哈希中搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Ruby中有以下散列:

I have the following hash in 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(方法:POST,路径:/ api / customer / 191023)

I would like to do a simple search within these hashes to find those whose the method key is set to POST and the path key set to "/api/customer/191023". The equivalent of data.where(method: "POST", path: "/api/customer/191023").

首先,我试着用 select 方法方法

 hs = hash.select{|k, h| h[:method] == "POST" }

但是返回的散列是空的。

But the returned hash is empty.

谢谢。

M。

推荐答案

我看到你在:method 键的值后有空格,所以试试 regexp 以匹配它,如下所示:

I saw what you have a space after the value of :method key, so try regexp to match it, like follows:

hs = hash.select {|k, h| h[:method] =~ /POST/ && h[:path] == '/api/customer/191023' }

最高频率做:

To find host value with highest frequency do:

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

这篇关于在包含哈希的哈希中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆