Reputation: 10885
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
Upvotes: 0
Views: 45
Reputation: 11167
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
Upvotes: 1
Reputation: 16403
array_of_ips.group_by{|a| a.ip[0, a.ip.rindex(".")]}.each{|_, v| v.map!{|a| a.id}}
Upvotes: 1
Reputation: 18567
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]}
Upvotes: 1