我正在尝试使用 ipaddr 按升序对一些 IP 地址进行排序。不知道为什么这不起作用。运行自定义排序后,顺序不受影响。
require 'ipaddr'
ip_array = Array.new
ip_array2 = Array.new
ip_array = ["d1.mysite.com",
"d3.mysite.com",
"d2.mysite.com",
"d6.mysite.com",
"d32.mysite.com",
"d5.mysite.com",
"d9.mysite.com",
"d34.mysite.com"]
## First, get IP addresses and push onto ip_array2
ip_array.each { |x| ip_array2.push(IPSocket::getaddress(x)) }
## Let's see the unsorted array contents
ip_array2.each { |x| puts x }
## Now, sort IP addresses in ip_array2
ip_array2.sort { |a,b| IPAddr.new( a ) <=> IPAddr.new( b ) }
## Let's see the sorted array contents
ip_array2.each { |x| puts x }
BEFORE SORT (1st 3 octets are identical)
xxx.xx.xx.78
xxx.xx.xx.114
xxx.xx.xx.54
xxx.xx.xx.57
xxx.xx.xx.58
xxx.xx.xx.79
xxx.xx.xx.81
xxx.xx.xx.100
AFTER SORT (1st 3 octets are identical)
xxx.xx.xx.78
xxx.xx.xx.114
xxx.xx.xx.54
xxx.xx.xx.57
xxx.xx.xx.58
xxx.xx.xx.79
xxx.xx.xx.81
xxx.xx.xx.100