这里考虑的是下面的记录数组
[#<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']
我想通过不考虑下面哈希形式的ip地址的最后一个点值来获取此数组中相同ip的ID。
{12.10.20 =&gt; [26,27,29],127.0.0 =&gt; [44,52],14.30.20 =&gt; [55]}
任何技巧?
由于
答案 0 :(得分: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]}
答案 1 :(得分:1)
array_of_ips.group_by{|a| a.ip[0, a.ip.rindex(".")]}.each{|_, v| v.map!{|a| a.id}}
答案 2 :(得分:1)
使用前三个IP组(demo)从数据库中获取记录,然后简单组将执行此操作
IpAddress.select("ip_addresses.id, substring(ip from '(([0-9]*\.[0-9]*){2})') as short_ip)").group_by(&:short_ip)
这将返回相关IPAddress的哈希值。如果你正在寻找id而不是Objects添加另一个循环:)
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