Sort IP Addresses Simply in Ruby

I was processing some XML nmap network scan data and as part of the output I ended up with arrays of unordered IP Addresses. Part of me felt dirty outputting the IPs in random order–it turns out sorting by IP is simple in ruby.

ips = ["10.100.0.9",  "10.220.0.1", "10.120.0.3", "10.130.0.1"]
 
puts ips
 
10.100.0.9
10.220.0.1
10.120.0.3
10.130.0.1
 
# sort_by will do natural sorting on whatever we pass it, so split the IP Address into an array of 
# integers on the '.' and then ruby will numerically sort by first array element, when they are equal 
# it will compare the second array element etc--perfect
ips.sort_by! {|ip| ip.split('.').map{ |octet| octet.to_i} }
 
puts ips
 
10.100.0.9
10.120.0.3
10.130.0.1
10.220.0.1