0

consider here is array of records below

   [#<IpAddress id: 26, ip: "12.10.20.11", latitude: '0.3155460609',  longitude: '0.74357158' ,
    #<IpAddress id: 27, ip: "12.10.20.12", latitude: '0.3155460609',  longitude: '0.74357158',
    #<IpAddress id: 29, ip: "12.10.20.30", latitude: '0.3155460609', longitude: '0.74357158',
    #<IpAddress id: 44, ip: "127.0.0.1", latitude: '0.3155460609', longitude: '0.7435715',
    #<IpAddress id: 52, ip: "127.0.0.3", latitude: '0.3155460609', longitude: '0.743571' ,
    #<IpAddress id: 55, ip: "14.30.20.13", latitude: '0.3155460609', longitude: '0.74357']

I want to get ids of same ip's in this array by not considering last dot value of ip address in form of hash like below.

{12.10.20 => [26,27,29] , 127.0.0 => [44,52], 14.30.20 => [55]}

Any trick?

Thanks

3 Answers 3

1
h = Hash.new {[]}
records.each { |ipaddr| ip = ipaddr.ip; h[ip[0...ip.rindex(".")]] <<= ipaddr.id }
puts h
# => {"12.10.20"=>[26, 27, 29], "127.0.0"=>[44, 52], "14.30.20"=>[55]}  
Sign up to request clarification or add additional context in comments.

Comments

1
array_of_ips.group_by{|a| a.ip[0, a.ip.rindex(".")]}.each{|_, v| v.map!{|a| a.id}}

Comments

1

Fetch records from database with first three IP groups( demo ), then simple group will do the trick

IpAddress.select("ip_addresses.id, substring(ip from '(([0-9]*\.[0-9]*){2})') as short_ip)").group_by(&:short_ip)

This will return hash of related IPAddress. If you are looking for ids instead of Objects add another loop :)

    IpAddress.select("ip_addresses.id, substring(ip from '(([0-9]*\.[0-9]*){2})') as short_ip)").group_by(&:short_ip).inject({}).map do |key, records| { key: records.pluck(:id)} end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.