B
barjunk
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"
}
Mike B.
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"
}
Mike B.