IPAddr as hashtable key?

N

Neil Spring

I'm wondering if the methods required for using IPAddrs as
keys in a Hash would be useful.

I made the mistake (oops) of maintaining a dns name cache
keyed on IPAddrs. I've fixed my problem, but I think the
following methods should be added to ipaddr.rb.

class IPAddr
def hash
@addr
end
alias eql? ==
end

thoughts? Is this feature missing for a reason I don't see?
example code follows.

thanks,
-neil



skyo:~> cat myipaddr.rb

require 'ipaddr'
class IPAddr
def hash
@addr
end
alias eql? ==
end


skyo:~> ruby1.8 -r ipaddr -e 'puts IPAddr.new("10.0.0.1").eql?(IPAddr.new("10.0.0.1"))'
false

skyo:~> ruby1.8 -I . -r myipaddr -e 'puts IPAddr.new("10.0.0.1").eql?(IPAddr.new("10.0.0.1"))'
true

skyo:~> ruby1.8 -r ipaddr -e 'puts IPAddr.new("10.0.0.1").hash, IPAddr.new("10.0.0.1").hash'
537145508
537145438

skyo:~> ruby1.8 -I . -r myipaddr -e 'puts IPAddr.new("10.0.0.1").hash, IPAddr.new("10.0.0.1").hash'
167772161
167772161

skyo:~> ruby1.8 -r ipaddr -e 'a=IPAddr.new("10.0.0.1"); foo = { a => true }; puts foo[IPAddr.new("10.0.0.1")]'
nil

skyo:~> ruby1.8 -I . -r myipaddr -e 'a=IPAddr.new("10.0.0.1"); foo = { a => true }; puts foo[IPAddr.new("10.0.0.1")]'
true
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,231
Members
46,820
Latest member
GilbertoA5

Latest Threads

Top