Search within a Hash containing hashes

2019-06-13 08:23发布

问题:

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\"
    }
}

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").

First, I've tried with a select only based on method:

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

But the returned hash is empty.

Thank you.

M.

回答1:

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