Search code examples
ruby-on-railsrubyhaship-addresscidr

Refer to a hash where the key is an ip_address


I've got a model that I need to group by the :sending_ip, which is a "cidr" column in the database.

@count_hash = Webhook.group('sending_ip').count

Resulting in this hash:

{#<IPAddr: IPv4:213.32.165.239/255.255.255.255>=>127000, #<IPAddr: IPv4:153.92.251.118/255.255.255.255>=>228000}

I cannot figure out how to reference this type of key. Below are some examples of the ways that I've tried to call these keys. All of them return nil or error.

@count_hash[#<IPAddr: IPv4:213.32.165.239/255.255.255.255>]

@count_hash["#<IPAddr: IPv4:213.32.165.239/255.255.255.255>"]

@count_hash[<IPAddr: IPv4:213.32.165.239/255.255.255.255>]

@count_hash["#<IPAddr: IPv4:213.32.165.239/255.255.255.255>"]

Elsewhere in my app, I've got a simpler example that works great. The other example groups by esp, which results in this hash:

{"hotmail"=>1000, "gmail"=>354000}

The second hash, I can refer to easily

@count_hash["gmail"]

To obtain the expected result of 354000

How can I achieve this same functionality with the previous hash that was grouped by sending_ip? Thank you in advance for your insight.


Solution

  • This:

    #<IPAddr: IPv4:213.32.165.239/255.255.255.255>
    

    is the result of calling #inspect on an instance of IPAddr. So the keys are IPAddr instances and you can say:

    ip = IPAddr.new('213.32.165.239')
    @count_hash[ip]
    # 127000
    

    Or you could iterate over the hash:

    @count_hash.each { |ip, n| ... }
    

    or over its keys:

    @count_hash.keys.each { |ip| ... }
    

    depending on what you need to do. You could even convert the keys to strings if that's more convenient:

    @count_hash = @count_hash.transform_keys(&:to_s)
    # or
    @count_hash.transform_keys!(&:to_s)