Differences

This shows you the differences between two versions of the page.

Link to this comparison view

sort_ip_addresses_simply_in_ruby [2019/08/08 15:23] (current)
Line 1: Line 1:
 +====== 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.
 +
 +<sxh 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
 +</sxh>
 +
 +===== References =====
 +  - http://tech.maynurd.com/archives/124
 +
  
Print/export
QR Code
QR Code sort_ip_addresses_simply_in_ruby (generated for current page)