Slinky
Slinky

Reputation: 5832

Sorting IP Addresses in Ruby 1.8

I am trying to sort some ip addresses in ascending order using ipaddr. Not sure why this is not working. After I run my custom sort, the order is not affected.

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

Upvotes: 0

Views: 1804

Answers (1)

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70989

sort is not in place. Either call sort! or assign the result from sort to ip_array2.

Upvotes: 2

Related Questions