On Sep 24, 6:31 pm, barjunk <barj... / attglobal.net> wrote: > I'm having to sort some IP addresses that are stored in a hash. I > came up with the code below to accomplish the task. I have two > questions: > > - What if any is a better way to have done this? > - Given that the hash has to be the mac address, could I store the > hash values in a different way to make this easier? > > require 'ipaddr' > > hash={} > hash["00:19:d2:7b:55:10"]=["c","12.12.19.11",3] > hash["00:18:39:0d:a1:e9"]=["b","12.12.19.83",1] > hash["00:11:50:18:0c:0e"]=["a","12.12.19.81",2] > > #the second index is the value item to sort by. > #this particular sort would fail if [1][1] was not an IP address > > sortedarray = hash.sort { |a,b| > IPAddr.new(a[1][1]).to_i <=> IPAddr.new(b[1][1]).to_i > > } > > sortedarray.each { |item| > > print "mac:", item[0] + "\n" > print "IP:", item[1][1] + "\n" > > } # May not be faster, but doesn't rely on the ipaddr library hash={} hash["00:19:d2:7b:55:10"]=["c","1.12.19.11",3] hash["00:18:39:0d:a1:e9"]=["b","12.12.19.83",1] hash["00:11:50:18:0c:0e"]=["a","12.12.19.81",2] hash["00:00:00:08:c3:1e"]=["a","2.12.19.81",2] hash["fe:00:00:08:c6:2f"]=["a","204.12.19.81",2] sorted_array = hash.sort_by{ |mac, settings| # Break the IP into an array of integers # sort_by will sort by the first entry first, then the second, and so on settings[1].split('.').map{ |digits| digits.to_i } } # Note that you can break apart the array of arrays in the iteration # And use puts and string interpolation for simpler printing sorted_array.each { |mac, settings| puts "mac: #{mac}" puts "IP: #{settings[1]}" }